1

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 :)

2
  • 3
    See $.getJSON() here : api.jquery.com/jQuery.getJSON Just echo your json_encode($dates); Commented Apr 29, 2013 at 12:38
  • 1
    Use echo and EXIT() after it (so no other code is send later) Commented Apr 29, 2013 at 12:39

3 Answers 3

6

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

Comments

0

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> 

Comments

0

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; 

1 Comment

This doesn't actually show the OP how to pass the JSON data to jQuery.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.