Reputation: 11
I'm a JS newbie ... I've got a PHP page w/ a JavaScript function which makes a JSON call to a database server. That JSON function returns an array, which I need to parse and do something with. I understand the need for the callback (currently getting the undefined errors), but am confused as to the actual syntax. Can anyone provide a bit of guidance?
Here's my JSON function in the PHP Page:
var GETDATA = function()
{
$(document).ready(function()
{
$.getJSON('api.php', function(data)
{
$.each(data, function(key, val)
{
UpdateGraph(val.x, val.y, val.z);
});
});
});
};`
**The UpdateGraph function takes the variables and performs some further business logic
The api.php page connects to a database, grabs a recordset, and puts it into a JSON array. the last line of that is
echo json_encode($arr);
I understand the asym flow of this, and that I need a callback function to fire when the data is received ... but I'm lost in how to make this happen. Any guidance would be most appreciated.
Upvotes: 1
Views: 1417
Reputation: 1
Your returned json object (data) should also have a key value relationship for each nested object inside "data". To put in a simple phrase...treat json object like a hash map with key/value
so say i have two object :object a and object b inside "data"
$.each(data.a, function(key, val){
UpdateGraph(val.x, val.y, val.z);
});
$.each(data.b, function(key, val){
UpdateGraph(val.x, val.y, val.z);
});
are valid
Upvotes: 0
Reputation: 1345
First of all, JSON is a format, not a language.
You already have the callback
$.getJSON('api.php', function(data)
function(data) is your callback, and data is your returned data from php, inside of it you should add your code or what you want to do with the data.
$.each(data, function(key, val){
UpdateGraph(val.x, val.y, val.z);
});
$.each will cycle through your data array and call the UpdateGraph function
Upvotes: 1