How do I pass JSON from PHP to jQuery
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 :)
Answer
Solution:
Send json header at the beginning of your php file:
And pull the json with jquerys getJSON function:
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:
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.