How do I pass JSON from PHP to jQuery

445

I am trying to get data from a database with PHP and passing it to jQuery so I can use it in a dynamic google chart. I have converted my PHP array to JSON with json_encode() but now I have to access this data with jQuery to pass it to the google chart.

My PHP code:

$db = new Db(DB_NAME, DB_HOST, DB_USER, DB_PASSWORD);

$dates = array();
for($number=14; $number>=1; $number--) {
    $dateValue = date('j M', strtotime("-$number day"));
    $getCount[$number] = $db->get($this->styleName, $dateValue);
    $items[$dateValue[$number]] = $getCount[$number];
}
$json_encode = json_encode($dates);
var_dump($json_encode);

My outputted JSON:

{
"15 Apr": "19",
"16 Apr": "15",
"17 Apr": "18",
"18 Apr": "13",
"19 Apr": "27",
"20 Apr": "2",
"21 Apr": "12",
"22 Apr": "9",
"23 Apr": "11",
"24 Apr": "20",
"25 Apr": "25",
"26 Apr": "137",
"27 Apr": "99",
"28 Apr": "115"
}

My main question is how do I pass this data to my jQuery script? Can someone say me if I am doing this the right way or help me to get on the right track?

Thanks in advance :)

762

Answer

Solution:

Send json header at the beginning of your php file:

<?php
header('Content-Type: application/json');
// build $datas
echo json_encode($datas);
?>

And pull the json with jquerys getJSON function:

$.getJSON('path/to/php/file.php', function(jsondata) {
    // use jsondata here
});
138

Answer

Solution:

you could do it in a seperate request, so your request only output the json and fetch it with $.getJson(); It is a clean way but requires an extra request;

or you can include it in tags in the html

output template:

<html>
  ...
  ...
  <script type="text/javascript">
    $.yourOwnJqueryExtention.setJSON(<?=$myJSON?>); 
  </script>
</body>
</html>
519

Answer

Solution:

much simpler, you don't need to change header info(this is hardly possible in Wordpress for example), just convert encoded object to string.

$json_encode = (string)$json_encode;

People are also looking for solutions to the problem: Retrieve data from database in PHP and display them in JQuery on the same page

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.