Kyle
Kyle

Reputation: 1

JQuery Ajax call, return value problem

function getMore(from){
 var initData = "&start-index=";
 initData += from;
 $.ajax({
  type:"POST",
  url: '', //removed the URL
  data: initData,
  dataType: 'json',
  success: function(result) {
   return result;
  },
  error: function(errorThrown) {

  }
 });

 return result;
}

Its a google base query; I have another function that makes the initial server call and gets the first 250 items. I then have a running counter and as long as the results = 250 it calls the server again, but starting at "start-index=" of the current amount of items pulled off. This part all works correctly and with firebug I can also see that the server response is proper JSON.

The trouble I'm having is trying to return the JSON from this function to the function that called it. I do not want to call the original function again because it will clear the arrays of data already pulled from the server. Each time it returns to the parent function it's null.

Does anyone know how i can go about returning the data using "return"?

Upvotes: 0

Views: 482

Answers (2)

andres descalzo
andres descalzo

Reputation: 14967

function FuncionCallGetMore(){
    //...    
    getMore('x-value', FuncionGetReturn);
    //...
}  

function FuncionGetReturn(error, value){
   if (!error) {
       // work value
   }
}

function getMore(from, fn){

  var initData = "&start-index=" + from;

  $.ajax({
    type:"POST",
    url: '', //removed the URL
    data: initData,
    dataType: 'json',
    success: function(result) {
      fn(false, result);
    },
    error: function(errorThrown) {
      fn(true);
    }


    });

    return;
}

Upvotes: 1

Justin Johnson
Justin Johnson

Reputation: 31300

The only way that you can do what you're describing is to make the AJAX call synchronous, which you don't want to do since it will lock the UI thread while the request is being made, and the browser may will to freeze. No one likes freezing.

What you want to do is use callbacks. Post the code of the other functions involved so I can get a better idea of what is going on. But basically, what you want to do is to create an asynchronous loop.

function listBuilder() {
    var onError = function(response) {
        // ...
    };
    var onSuccess = function(response) {
        // Handle the items returned here

        // There are more items to be had, get them and repeat
        if ( response.length == 250 ) {
            getMore(onSuccess, onError, 250);
        }
    };

    getInitialSet(onSuccess, onError);
}

function getMore(onSuccess, onError, from) {
    $.ajax({
        type:"POST",
        url: '', //removed the URL
        data: "&start-index=" + from,
        dataType: 'json',
        success: onSuccess,
        error: onError
    });
}

Upvotes: 0

Related Questions