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; });
source share