Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a value with jQuery each() function

i'm new to javascript, and I would like to retrieve values from JSON and push it into an array so that I can parse again this array in another function, But I don't know how to return the array after pushing element inside it.

In the following script I can't display values in items

function gC(b,c,p) {

    $.getJSON('getmonths', 'b='+b+'&c='+c+'&p='+p, processJSON);    
}

function processJSON(data) {
      var retval = [];
      $.each(data, function(key, val) {

          retval.push(val); 
          //alert(retval.pop());
      });
      return retval;
}

    $(document).ready(function(){
       var b = $("#b").val();
       var c = $("#c").val();
       var p = $("#p").val();

       var items = [];

       items = gC(b,c,p);
       var i = 0;

       $('td').each(function(index) {
          $(this).attr('bgcolor', items[i]);
          i++;
       }

How could I access the array ?

thank !

like image 482
Jerec TheSith Avatar asked Aug 04 '11 13:08

Jerec TheSith


1 Answers

You don't return from an AJAX call, you have it call a callback function when it's done.

function gC(b,c,p) {
    var retval = [];
    $.getJSON('getmonths', 'b='+b+'&c='+c+'&p='+p, processData);
}

function processData(data){
  var retval = [];
  $.each(data, function(key, val) {
      retval.push(val); 
      //alert(retval.pop());
  });
  alert(retval);
}

processData would be called when the AJAX call is done. This can't return a value to another function, so all your logic has to be inside this callback function.

UPDATE: You can also pass in a callback function to gC to be called when it's done.

function gC(b,c,p,f) {
    var retval = [];
    $.getJSON('getmonths', 'b='+b+'&c='+c+'&p='+p, function(d){
       if(typeof f == 'function'){
         f(d);
       }
    });
}

Then you call gC like so:

gC(b,c,p,function(data){
    var retval = [];
    $.each(data, function(key, val) {
        retval.push(val); 
        //alert(retval.pop());
    });
    alert(retval);
});

UPDATE2: I saw the code you added to the question. This needs to be done in the callback.

gC(b,c,p,function(data){
    var items = [];
    $.each(data, function(key, val) {
       items.push(val);
    });
    $('td').each(function(index){  // You don't need a separate i variable
                                   // you can just use the index from the loop
      $(this).attr('bgcolor', items[index]);
   }
})
like image 174
Rocket Hazmat Avatar answered Oct 06 '22 00:10

Rocket Hazmat