I have created a generic function that gets data from the server via jQuery's AJAX call. When successfully retrieving the data, I'd like to call another function that I'm passing in (e.g. functionAfterSuccess in the below code example).
This passed in function is getting called, but it seems to be executing right away and not "waiting" until the successfully retrieving the data from the server.
Does the passed in function (functionAfterSuccess) get executed at the same time as the main function (genericAJAXGet)? Not sure what I'm doing wrong.
// calling function
$('#run').on('click' , function() {
var $url = '/getdata';
var $dataToSend = { id: '123', data: 'ABC' };
genericAJAXGet("POST", $url, $dataToSend, "json", myFunction($param1));
});
// generic AJAX function
function genericAJAXGet($type, $url, $dataToSend, $returnDataType, functionAfterSuccess) {
// build ajax request
var $request = $.ajax({
type: $type,
url: $url,
data: $dataToSend,
dataType: $returnDataType
});
// Process a successful response
$request.done(function(data) {
if(data.error) {
alert('uh oh');
} else {
// successfully returned data, but there was some application logic
if (data["type"] == "issue") {
alert('app logic issue');
} else {
// only run the passed in function when the data is successfully retrieved
functionAfterSuccess;
}
}
});
// Process a failed response
$request.fail(function() {
alert('request failure');
});
}
// Other function to be called that is being passed in as a parameter
function myFunction($param1) {
alert($param1);
}