0

Basically I need to to return a variable from inside of a function using an ajax call.

Like so:

function returnStuff(){
  $.ajax({
    //do stuff
  }).done(function(response){
    return response;
  })
return response;
}

I can't just use a variable in the done function and return that because the function will just return the undefined variable before the call completes.

Is there any way that I can return a variable through 2 layers of functions or is there a way that I can wait to return until the call is complete?

  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Arun P Johny Jan 10 '14 at 02:49

2 Answers2

2

No. You cannot synchronously wait/block in JavaScript. Best you can do is something like this:

function returnStuff(){
  return $.ajax({
    //do stuff
  }).done(function(response){
    // handle some stuff
  });
}

returnStuff().done(function() {
    // add a 2nd event handler (called after the one above)
});

You have to rearchitect your code to not depend on getting a result back immediately.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
-1

Use jquery ajax async option. This will make the request blocking instead of asynchronous - note this can cause the UI to lock up while the request is happening, so I agree with Mark that you should change your code architecture to not require setting async false, however this does answer your question.

function returnStuff(){
    var ret;
    $.ajax({
       async: false,
       //do stuff,
       success: function(response) {
         ret = response;
       }
     });
     return ret;
}

Please note there is a really good write-up explaining why you should not do this here: How do I return the response from an asynchronous call?

Community
  • 1
  • 1
Joel Cox
  • 3,289
  • 1
  • 14
  • 31
  • Thanks Sam, you're right - copy / paste and not checking fail on my part. Edited and fixed. – Joel Cox Jan 10 '14 at 03:08
  • It's also deprecated as of jQuery 1.8. But I'm curious how this was implemented... as an infinite busy loop I imagine? – mpen Jan 10 '14 at 21:41