1

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.

2
  • 1
    That's a JavaScript function. Functions don't exist in JSON since it is a data exchange format. The overall code looks "ok" though you probably don't need to use a .ready callback. Is the function executed? What is the value of data? What are the undefined errors you get? Commented Jun 8, 2012 at 18:26
  • what triggers the call to the API? is it a click event? or on load? Commented Jun 8, 2012 at 18:27

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.