views:

241

answers:

2

I would like to call jQuery JSON function and pass back results as JSON object (Javascript array?), but I am not quite understanding dynamics of what is happening here.

myJSON = myFunction(productNo)
$.each(myJSON, function(i,user){
   alert (user.description)
}


function myFunction(productNo)
{
  $.getJSON
  (
      "processors/process_1.php",
       { productNo: 'ABC' },                
       function(data)
       {        
           return data;
       }
   )        
}
A: 

What you're getting back is a native Javascript data structure (JSON stands for Javascript Object Notation. I'm not sure I understand your question either... are you asking what is happening here?

What you're doing right now is iterating over the properties of the data object you got back (which is in the JSON format). Are you expecting a list of user objects of some kind? Each one having a description attribute?

EDIT

Ok, so after reading your comment I think I've figured out your problem - since AJAX is asynchronous, you can only work on the data once the request has completed. That's why you're getting back undefined, because the browser continues executing the code without waiting for the request to complete. What you need to do here is work with the data in your callback:

function myFunction(productNo)
{
  $.getJSON(
      "processors/process_1.php",
       { productNo: 'ABC' },                
       function(data) {
           $.each(data, function(i, user){
                 alert (user.description)
           }
       }
   )        
}
Vivin Paliath
sorry the example is a bit contrived. The myJSON object returned is undefined. I can iterate thye object in the myFunction function, but not in above example when I pass back object as parm.
davidP
actually I am trying to make recyclable ajax functions that get a database record and pass back array to calling function. I think Gabe's idea is more workable.
davidP
+1  A: 

Ajax is asynchronous, so you cannot return something from the callback - it will not complete until after your calling function has exited. Instead you need to do all your work in the callback. You should use a closure to pass along the work you want to be done when the ajax call completes:

myFunction(productNo, function(myJSON) {
    $.each(myJSON, function(i,user){
       alert (user.description)
    }
});


function myFunction(productNo, onComplete)
{
  $.getJSON
  (
      "processors/process_1.php",
       { productNo: 'ABC' },                
       onComplete
   )        
}
Gabe Moothart
As a side note, there's no reason to use `$.each()`, since you don't need the index. Just use a for loop: `for(var user in myJSON){alert(user.description)}`. myJSON isn't JSON text; it's an actual array.
Isaac Cambron