Skip to content Skip to sidebar Skip to footer

How To Pass Php Variable To Jquery

i try to pass php variable to jquery ,i have try to use But it's not working success, when i try to use dataSource: insted dataSource: [ { childName: 'Child1', childId: 1, par

Solution 1:

You forget to echo your php variable

<?phpecho json_encode($data); ?>

plus, since you want it in json format, you have to parse it too and because of that you have to enclose your property name in double quotes.

your php variable will become:

$data= '[
    { "childName": "Child1", "childId": 1, "parentId": 1 },
    { "childName": "Child2", "childId": 2, "parentId": 2 },
    { "childName": "Child3", "childId": 3, "parentId": 1 },
    { "childName": "Child4", "childId": 4, "parentId": 2 }
]';

and dataSource will be:

dataSource: JSON.parse(<?phpecho json_encode($data); ?>)

Its working :)

 Its working :)

Solution 2:

The problem here is that you are trying to parse a string directly to JSON and by doing so you will get also the "new lines" and other characters escaped on the output string as you can see in this test:

http://sandbox.onlinephpfunctions.com/code/3c31cecddd99aee0562d09c84b9a8e5770c3444b

However you could achieve the output that you want passing a properly formatted array to the json_encode function instead of a string like so:

$data_array = array(
    array('childName' => "Child1",
          'childId' => "1",
          'parentId' => "1"),
    array('childName' => "Child2",
          'childId' => "2",
          'parentId' => "3"),
    array('childName' => "Child3",
          'childId' => "3",
          'parentId' => "3"),
    array('childName' => "Child4",
          'childId' => "4",
          'parentId' => "4"),          
);

echo json_encode($data_array);

/*
Output:
[{"childName":"Child1","childId":"1","parentId":"1"},
{"childName":"Child2","childId":"2","parentId":"3"},
{"childName":"Child3","childId":"3","parentId":"3"},
{"childName":"Child4","childId":"4","parentId":"4"}]
*/

Edit: as @mohammad-mudassir noted you also need to use JSON.parse to parse the string back to JSON.

dataSource: JSON.parse(<?php echo json_encode($data_array); ?>)

Post a Comment for "How To Pass Php Variable To Jquery"