views:

2255

answers:

3

I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.

1) How can I return the JSON encoded string to the javascript? 2) How will the javascript loop through the rows and access their fields?

+7  A: 

To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.

To loop through an array, I usually use jQuery.each():

var recordList = yourMethodToGetRecordListWithAjax();

jQuery.each(recordList, function()
{
    alert(this.Name); // For example
});
DrJokepu
There's a small typo in your answer, jquery.each should be $.each. Other than that it works good :)
Click Upvote
Here's my code: $.getJSON("getData.php",data,myFunctionToLoopThroughResults);
Click Upvote
$ is a shortcut for jQuery - I prefer to write jQuery for "static" things like each() and use $ for "non-static" things like queries as I believe it enhances readability.
DrJokepu
But it's really up to you and your personal taste.
DrJokepu
I tried using jquery but it gave me an error in firebug, so I dunno
Click Upvote
it's jQuery, not jquery. It is case-sensitive.
DrJokepu
careful with the first A in AJAX. `async: false` would probably be a good idea within that ajax call
geowa4
ahh .
Click Upvote
A: 

You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.

See above answer for the rest.

kylebrooks
A: 

1) in the php script:

$return["foo"]  = "bar";
$return["blah"] = "bleg";
print json_encode($return);

2) in the javascript:

      $.ajax({
      type: "POST",
      url: URL,
      cache:false,
      data: values,
      dataType:'json',
      success: function(json)
                   {
     var foo = json.foo;
                    if (json.blah == "bleg")
                    { 
                       // do stuff 
                    }

     }  // end success function
    });  // end ajax call
Lance Kidwell