get data returned inside success of $.ajax jquery

789 Views Asked by At

I have a question here. Let's say I have some Ajax with jQuery like so:

var jqXHR = $.ajax({
       type: 'POST', 
       success: function(data) {
             if(data != true)
             {
                  return false;
             }
       }
});

I know that $.ajax returns a jqXHR object. My question is the following:

Is it possible to get the returned value of the success function of my $.ajax call using that jqXHR object? If so, how do I do that? If that's not possible using the jqXHR object, is there any way that I can get access to the returned value of my success function WITHOUT SETTING async: false in $.ajax?

Any help please?

2

There are 2 best solutions below

1
On

It is not possible without setting async to false. I would suggest not to set it to false because it stops the page completely until the server response comes. Sometimes it even hangs the browser if the connection is slow or server takes time to respond due to heave operation.

You can execute your code in the success handler of ajax which you are planning to do it outside.

0
On

It is possible - in a way - returned jqXHR is also a deferred object so you could do

jqXHR.then(function(data) { ... });

the only other way to get access to the data that i know of apart of the ajax callbacks, the cool thing is that you can use it multiple times after the ajax request was sent and it will always return the data you've received from the server.