0

I am trying to pass a value from a php variable to a javascript variable. So instead of defining manually each time {"data": "Country"},{"data": "Customer Name"}... as you see below

<script type="text/javascript">
    $(document).ready(function () {

        $('#users').DataTable({
            "columns": [
              {"data": "Country"},
              {"data": "Customer Name"},
              {"data": "Order Number"},
              {"data": "Address"} 
            ],
            "processing": true,
            "serverSide": true,
            "ajax": {
                url: 'demo2.php',
                type: 'POST'
            }
        });
    });
</script>

Let's say I have a php variabe defined on the top of my html as below

<?php 
$jsColumns = '{"data": "Country"},{"data": "Customer Name"},{"data": "Order Number"},{"data": "Address"}';
?>

I want to insert this php variable inside my script

$('#users').DataTable({
    "columns": [
      <?php echo $jsColumns;?> 
    ],
    "processing": true,
    "serverSide": true,
    "ajax": {
        url: 'demo2.php',
        type: 'POST'
    }
});

It's not working inside the script but when i use echo $jsColumns; on the top in the php part i can see that the variable contains value. Any idea please what i am missing in my code ? Thank you very much.

JuniorDeveloper
  • 57
  • 1
  • 2
  • 6
  • Ideally what you are doing should work. Could you provide the entire php file? – xadhix Feb 28 '18 at 15:22
  • Not sure why my comment got deleted: remember that php and javascript are not only different languages, they are running on different machines (php on your web server, javascript in your user's browser). Thus they can only communicate through a few very specific means; see the duplicate question for those means. – KayakinKoder Feb 28 '18 at 15:30
  • What do you mean "It's not working inside the script"? Is the variable empty at that point? – Wizard Feb 28 '18 at 15:32

1 Answers1

0

What you are doing looks right, but special characters in your actual data may be causing problems, and will be insecure. You could make an array of data, and then use json_encode to escape it - e.g.

<?php

$jsColumns = array(
    array('data'=>'Country'),
    array('data'=>'Customer Name'),
    array('data'=>'Order Number'),
    array('data'=>'Address')
);

?>

then

$('#users').DataTable({
    "columns": <?php echo json_encode($jsColumns); ?>,
    "processing": true,
    "serverSide": true,
    "ajax": {
        url: 'demo2.php',
        type: 'POST'
    }
});
Chris Wheeler
  • 1,623
  • 1
  • 11
  • 18