In an effort to streamline my ajax calls, I have developed a JavaScript file that consolidates all of them. The code snippet below illustrates this common approach:
function doAjax(doAjax_params) {
var url = doAjax_params['url'];
var requestType = doAjax_params['requestType'];
var contentType = doAjax_params['contentType'];
var dataType = doAjax_params['dataType'];
var data = doAjax_params['data'];
var beforeSendCallbackFunction = doAjax_params['beforeSendCallbackFunction'];
var successCallbackFunction = doAjax_params['successCallbackFunction'];
var completeCallbackFunction = doAjax_params['completeCallbackFunction'];
var errorCallBackFunction = doAjax_params['errorCallBackFunction'];
//Make the ajax call
$.ajax({
url: getBaseURL() + url,
crossDomain: true,
type: requestType,
contentType: contentType,
dataType: dataType,
data: data,
success: function (data, textStatus, jqXHR) {
console.log(typeof successCallbackFunction);
debugger
successCallbackFunction(data);
},
error: function (jqXHR, textStatus, errorThrown) {
if (typeof errorCallBackFunction === "function") {
errorCallBackFunction(errorThrown);
}
}
});
}
This script receives parameters and generates an ajax request accordingly. It is stored in a file called APIHandler.js
.
I am attempting to invoke this function from various files, as demonstrated in the example below.
function RedirectToDashboard() {
var params = $.extend({}, doAjax_params_default);
params['url'] = `profile/5`;
params['successCallbackFunction'] = `testsuccess`;
doAjax(params);
}
function testsuccess() {
alert("success");
}
Although the function runs successfully, there is an issue with referencing the callback function. When executing
, it returns string instead of function.console.log(typeof successCallbackFunction);
I initially suspected the sequence of loading JavaScript files mattered. Both APIHandler.js
and the page-specific JS are loaded before the ajax call triggered by a button click event.
Additionally, I considered whether parameter passing might be incorrect, leading JS to interpret the function name as a string. However, research indicates that simply providing the function name should suffice.
Could there be any other oversight causing this behavior?