“I’m trying to make an Ajax call
, which is successful. But when I try to print the response it does not concatenate the "success" or "failure: string with "initial value"
it prints the middle vale and Also, if i put console.log
inside success or failure it prints the value. It does not work outside the Ajax call
loadData : function(groupRID, serviceName) {
var html = 'initial value';
var params = {
codeGroupRid : groupRID,
outputFormat : 'json'
};
html +=' middle'
Util.Functions.eAjax(serviceName, params, {
success : function(response) {
html += ' Success';
return html;
},
failure : function(errMsg) {
html += ' Failure';
return html;
}
});
},
Expected is - initial value middle Success
Actual is - initial value middle
Remove the return html;
part from success and failure callbacks cause ajax is asynchronous. If you use return inside the callback it return before response is obtained.
As @Gokul Raj K.N. said - Ajax is asynchronous method by default. So:
Recommended solution:
You should add function
parameter to loadData
method which can be done like:
loadData(groupRID, serviceName, function (result) {
let loaded_data = result;
// do something with loaded data
});
And loadData
method with callback
:
loadData : function(groupRID, serviceName, callback) {
var html = 'initial value';
var params = {
codeGroupRid : groupRID,
outputFormat : 'json'
};
html +=' middle'
Util.Functions.eAjax(serviceName, params, {
async: false,
success : function(response) {
html += ' Success';
callback(html);
},
failure : function(errMsg) {
html += ' Failure';
callback(html);
}
});
},
Not recommended solution:
You can easy change async
parameter to make it synchronous.
true if this request should run asynchronously. Setting this to false should generally be avoided, since it will cause the UI to be blocked, the user won't be able to interact with the browser until the request completes. Defaults to: true
loadData : function(groupRID, serviceName) {
var html = 'initial value';
var params = {
codeGroupRid : groupRID,
outputFormat : 'json'
};
html +=' middle'
Util.Functions.eAjax(serviceName, params, {
async: false,
success : function(response) {
html += ' Success';
return html;
},
failure : function(errMsg) {
html += ' Failure';
return html;
}
});
},