0

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 ???

1 Answer 1

1

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
(...)
Sign up to request clarification or add additional context in comments.

1 Comment

note that writing like this : var myArray = <?php echo json_encode($my_array)?>; is correct but will generate a confusion in syntax color if you are using an ide like eclipse or netbeans.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.