If you're using jQuery, you should definitely be using $.Deferred() and Promises/A. I've made this more verbose that you really need to demonstrate some of the functionality. $.ajax itself is already returning a $.Deferred().promise() so you can actually just cut out the extra step if you only need to make the one XHR request (see 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 verbose syntax comes in handy when you have multiple nested XHR requests and want to return the response of the inner-most call: deferredResponse.resolve(innerResponse). Here's the simply 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;
});