JS: result of returning from ajax nested success function

How to return the result of a nested ajax call as a result of the parent function?

//Declaring the function var myFunction = function(myData){ $.ajax({ type:'post', url:"/ajaxPage.php", data:{data:myData}, success:function(r){ return r; }); } //Calling the function var theResult = myFunction(myData); 

I want the 'theResult' variable to contain the contents of the ajax call.

+4
source share
4 answers

You will need to make an AJAX synchronous call (not asynchronous by default).

Something like that:

 //Declaring the function var myFunction = function(myData){ var returnValue = null; $.ajax({ type:'post', async: false, url:"/ajaxPage.php", data:{data:myData}, success:function(r){ returnValue = r; }); return returnValue; } //Calling the function var theResult = myFunction(myData); 
+2
source

Since ajax is asynchronous, you cannot return it to the parent function. What you can do is provide a callback function, and you also call it the result.

  //Declaring the function var myFunction = function(myData, callback){ $.ajax({ type:'post', url:"/ajaxPage.php", data:{data:myData}, success:function(r){ callback(r); }); } //Calling the function var theResult = myFunction(myData, function(res) { // deal with it.. }); 
+6
source

If you are using jQuery, you should definitely use $.Deferred() and Promises/A I made it more detailed that you really need to demonstrate some features. $.ajax itself already returns $.Deferred().promise() , so you can just cut an extra step if you only need to make one XHR request (see the bottom example).

 //Declaring the function var myFunction = function(myData){ var deferredResponse = new $.Deferred(); $.ajax({ type: 'post', url: '/ajaxPage.php', data: {'data': myData} }).done(deferredResponse.resolve).fail(deferredResponse.reject); return deferredResponse.promise(); } //Calling the function $.when(myFunction(myData)).done(function(response){ var theResult = response; }); 

The detailed syntax comes in handy when you have several nested XHR requests and want to return the response of the innermost call: deferredResponse.resolve(innerResponse) . Here is just a version.

 //Declaring the function var myFunction = function(myData){ return $.ajax({ type: 'post', url: '/ajaxPage.php', data: {'data': myData} }); } //Calling the function myFunction(myData).done(function(response){ var theResult = response; }); 
+3
source

Try the following:

 var myFunction = function(myData){ $.ajax({ type:'post', url:"/ajaxPage.php", data:{data:myData}, success:function(r){ return arguments.callee(r); }); } //Calling the function var theResult = myFunction(myData); 
+1
source

Source: https://habr.com/ru/post/1344901/


All Articles