I'm new to javascript and trying to understand if following thing is possible:
Let's say I use following ajax request construction in several places in my code (with different success callback functions - in this example only handleSuccessCallback()) and different url and data request param:
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: data,
error: errorCallback,
success: function(response) {
this.handleSuccessCallback(response);
}
});
function handleSuccessCallback(response) {
Do something with response here...
}
I wanted to refactor this code in such way, that I don't need to create construction above each time I need to send request. I wanted to create a function in my utils class that will take url, request data and error/success callback. Something like this:
function sendAjaxRequest(url, data, errorCallback, successCallback)
jQuery.ajax({
type: 'GET',
url: url,
data: data,
error: errorCallback,
success: successCallback
});
}
Then, I wanted to call this function several times passing different arguments from my main script.
In my main code:
var url = "https://some url";
var data = {};
var errorCallback = handleErrorCallback();
var successCallback = handleSuccessCallback(); // ??? This function requires `response` argument being passed, how it can be done?
utils.sendAjaxRequest(url, data, errorCallback, successCallback);
function handleSuccessCallback(response) {
Do something with response here...
}
function handleErrorCallback() {
Do something with error here...
}
However, what I don't understanding is the following:
how can I pass success callback function (handleSuccessCallback(response)) to the sendAjaxRequest() function, if my handleSuccessCallback(response) needs params which is result of the success ajax callback itself(response)?
How can I pass this response param to handleSuccessCallback() when passing it to sendAjaxRequest() if I don't know yet what will be the response from ajax call?
1 Answer 1
When you want to call:
function sendAjaxRequest(url, data, errorCallback, successCallback)
You just need to give names of functions for errorCallback and successCallback. You are passing function references, so they can be called by other code. The params are provided at the point where those functions are called, like in your original example:
success: function(response) {
this.handleSuccessCallback(response);
}
Here the success function as defined in ajax with first parameter as response, so you have an anonymous function here with the first parameter as response.
So you just need to define your functions to match what they will be when they get called by ajax, e.g.:
var firstSuccessCallback = function(response) {
//do something;
}
var firstErrorCallback = function(error) {
//do something;
}
you can do:
sendAjaxRequest(url, data, firstErrorCallback, firstSuccessCallback)