10

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.

4 Answers 4

10

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; 
});       
4
  • This is deffo what I need, I just need to make it work xD Tried putting an alert inside getJson but it never activates.
    – Vlad
    Commented Jul 17, 2012 at 6:48
  • 1
    I think there's a parenthesis error in function(jsonData)){, should be function(jsonData) { no ? Can't get either one to work though, just gonna hammer at it for a while :)
    – Vlad
    Commented Jul 17, 2012 at 6:49
  • if the alert don't show, maybe there is an error somewhere apart from the code you're showing. When I'm debugging things like this, I usually look at my firebug console just to check on things.
    – Leon
    Commented Jul 17, 2012 at 7:18
  • Got some code to work now as shown above, but having difficulties reaching the nested information, can only get the outer keys. Any suggestions?
    – Vlad
    Commented Jul 17, 2012 at 7:43
5

Try the jQuery documentation: http://api.jquery.com/jQuery.getJSON/

This example should get you started:

$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

This example is based on the JSON structure being;

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}
2
  • Ahh nice, thanks alot :) This works for $.getJSON('json.php') as well?
    – Vlad
    Commented Jul 17, 2012 at 6:26
  • Yeah just substitute whatever URL you need - the data returned by php will have to be JSON encoded. json_encode(); Commented Jul 17, 2012 at 6:29
3

Do not use echo in PHP. It will print string not JSON.

Use json_encode to pass JSON to javascript.

Use can use each to get the values in JSON at javascript end.

Example

http://www.darian-brown.com/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/

3
  • Ah cheers! Was mostly printing just to see that I got the syntax right, but always good to know.
    – Vlad
    Commented Jul 17, 2012 at 6:26
  • 1
    I given a example link. Check it. Commented Jul 17, 2012 at 6:28
  • Do I still need to echo the json_encode though like in this example? darian-brown.com/…
    – Vlad
    Commented Jul 17, 2012 at 6:54
2

If you are using JQuery there is a really simple solution to your approach as you can see here: http://api.jquery.com/jQuery.getJSON/.

Otherwise I just want you to explain that there is no way to access your JSON directly in JavaScript as you tried in your code above. The main point is, that JavaScript runs on your browser while your PHP script runs on your server. So there must definitely be a communication between them. So you have to request the data from the server over http I would suggest.

HTH

1
  • I thought the .getJson function is an Ajax-driven function that can grab Json data from any file? I was really not sure how to use it, I find this very confusing. I appreciate your answer however :)
    – Vlad
    Commented Jul 17, 2012 at 6:53

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.