How to return an array from jQuery ajax success function properly? [duplicate] How to return an array from jQuery ajax success function properly? [duplicate] ajax ajax

How to return an array from jQuery ajax success function properly? [duplicate]


In your code, you are looking for groups using procedural coding after the ajax call was made. The main problem is that you are looking for groups before the ajax call is complete.

Another problem is that you are returning groups to the success() function, but the TheObject.getArray() function returns nothing.

So you need to bring in the callback into the ajax function like this:

TheObject = {    getArray: function(callback) {        var groups = new Array;        $.ajax({              type: "POST",              url: "link.php",              success: function (data){                  var counter = 0;                  $('g',data).each(function(){                          var group_name = $(this).find("name").text();                      var group_id = $(this).find("id").text();                      var group = {                         id: group_id,                         name: group_name                      }                      groups[counter] = group;                      counter++;                  });                  callback.call(this,groups);              }         });     }}TheObject.getArray(function(a) {    // this code runs when the ajax call is complete    alert(a);});


A very simple version of David's example.

TheObject = {    getArray: function(callback) {         $.ajax({              cache: true,              type: "GET",              url: "http://www.domain.com/core/domains.php",              success: function (data){                   callback.call(this,data);              }         });     }}TheObject.getArray(function(data) {    javascript: console.log(data);    });


Use push on the array. Also you want to create a type called Group and then create a new group in the loop and then push it into the array.