Jquery Ajax Request Not Able To Return Data To Other Function
I am making a simple ajax request using jquery . Below is my ajax function . var makeJqueryAjaxRequest = function(arrParam) { var request = $.ajax({ url
Solution 1:
You can't return value from an Asynchronous callback function.
Because success
is a async
callback which is called by jQuery when a ajax Event(success in this case) fires. So returning something from this functions will not have any effect as they will be returned to jQuery code.
You can use the following
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type']
});
return request;
}
Then do
makeJqueryAjaxRequest(items).done(function(data){
if(data){
var msg = data;
// do whatever you like with msg now
}
});
Alternative Callback Approach:
var makeJqueryAjaxRequest = function(arrParam,callback) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
callback(data);
}
}
});
}
Then use it like
makeJqueryAjaxRequest(items,function(data){
// do whatever you like with data
});
Doc on $.ajax()
Note
And with either of these approach async: false
is not necessary. You can remove that. As the doc says
As of jQuery 1.8, the use of async: false is deprecated
Post a Comment for "Jquery Ajax Request Not Able To Return Data To Other Function"