ltdev
ltdev

Reputation: 4497

Javascript files without any php code

I'd like some help please. In order to keep separate the php functionality from the javascript I usually do something like this:

1st. Create a script inside the <head> tags where I keep all the variables that come from php, example:

<head>
<script>
   var url = "<?php echo site_url() ?>admin/products";
   // etc etc
</script>
</head>

2nd. Then in my file.js I can access the variables and do whatever I want to do with javascript and jquery.

<script src="path/to/some/file.js"></script>

// then in my script in file.js I can do whatever I want
url : url,
etc etc

This works fine but there might be some cases where I have some settings for plugins set dynamically, like this for example:

$('.dataTable').DataTable({
      'bProcessing' : true,
      'bServerSide' : true,
      'sAjaxSource' : url, // this is '<?php echo site_url() ?>admin/products', as above
      'sServerMethod' : 'POST',
      'pagingType': 'full_numbers',

      'columns': [
           <?php foreach($my_array as $item): ?> // *
            { 'data': '<?php echo $item; ?>' },
           <?php endforeach; ?>
       ],

So the * portion should be something like this in pure javascript

'columns': [
     { 'data': 'Title' },
     { 'data': 'Description' },
     etc etc
],

How can I do same thing in these cases, so there won't be any php inside my js scripts ???

Upvotes: 0

Views: 50

Answers (1)

ThinkTank
ThinkTank

Reputation: 1191

Why dont you continue on the same way ? Does this works for you ?

Head

<script>
   var url = "<?php echo site_url() ?>admin/products";
   var myArray = <?php echo json_encode($my_array)?>;
</script>

JS

(...)
'pagingType': 'full_numbers',
'columns': myArray
(...)

Upvotes: 1

Related Questions