How to get JSON from PHP to JS?

Tom picture Tom · Jul 17, 2012 · Viewed 40.7k times · Source

I have really been searching for almost 2 hours and have yet to find a good example on how to pass JSON data from PHP to JS. I have a JSON encoding script in PHP that echoes out a JSON script that looks more or less like this (pseudocode).

{
"1": [
  {"id":"2","type":"1","description":"Foo","options:[
    {"opt_id":"1","opt_desc":"Bar"},
    {"opt_id":"2","opt_desc":"Lorem"}],
  {"id":"3","type":"3","description":"Ipsum","options:[
...
"6":
  {"id":"14","type":"1","description":"Test","options:[
...
etc

Problem is, how can I get this data with JavaScript? My goal is to make a .js script that generates a poll based on these JSON datas, but I honest to god can't find any examples on how to do this. Guessing it is some something like:

Obj jsonData = new Object();
jsonData = $.getJson('url',data,function()){
  enter code here
}

Any links to any good examples or similar would be highly appreciated. And I thought that encoding the data in PHP was the tricky part...

EDIT:

I got this code snippet to work, so I can review my whole JSON data in JS. But now I can't seem to figure out how to get to the inner data. It does print out the stage number (1-6) but I can't figure out how to get the question data, and then again the options data within each question. Do I have to experiment with nested each loops?

$(document).ready(function()
    {       
        $('#show-results').click(function() 
        {
            $.post('JSAAN.php', function(data) 
            {
                var pushedData = jQuery.parseJSON(data);
                $.each(pushedData, function(i, serverData)
                {
                    alert(i);
                })
            })
        })
    });

The idea here is to get into the question information in the middle level and print out the qusetion description, then based on the question type - loop through the options (if any) to create checkbox/radiobutton-groups before going on to the next question. The first number represents which stage of the multi stage poll I am currently working on. My plan is to divide it into 6 stages by hiding/showing various divs until the last page where the form is submitted through Ajax.

Answer

Leon picture Leon · Jul 17, 2012

Not sure but I think, you can use

$.getJSON('url', data, function(jsonData) {                       
  // operate on return data (jsonData)    
});

now you can access and operate on the PHP json data, if you're going to use it outside the getJson call you can assign it to a variable

var neededData; 
$.getJSON('url', data, function(jsonData) {
    neededData = jsonData; 
});