Manikandan K Manikandan K - 4 months ago 18
Ajax Question

Is there a way to get responseText with async true using Jquery Ajax

Hi I have a situation that I have to return responseText with async true.

var initAjax = function (){
var customAjaxResponse = $.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function (xhr) {
$(".preloader div").removeClass('hide');
}
}).done(function (jsondata) {
$(".preloader div").addClass('hide');
try {
return jsondata;
} catch (e) {
generate("error", '<div class="activity-item"> \n\
<i class="fa fa-ban text-warning"></i> <div class="activity">Sorry! we are unable to find requested data, kindly try after some times.</div></div>');
}
}).error(function (jqXHR, exception) {
var error = "";
if (jqXHR.status === 0) {
error = "No internet Connection found.";
} else if (jqXHR.status == 404) {
error = "Page not found.";
} else if (jqXHR.status == 500) {
error = "Internal server error occurred.";
} else if (exception === 'parsererror') {
error = "JSON Parse error occurred.";
} else if (exception === 'timeout') {
error = "Your request has been timed out.";
} else if (exception === 'abort') {
error = "Ajax request has been aborted unexpectedly";
} else {
error = "Uncaught error occurred - " + jqXHR.responseText;
}
generate("error", '<div class="activity-item"> \n\
<i class="fa fa-ban text-warning"></i> <div class="activity">' + msg + '</div></div>');
});
return customAjaxResponse.responseText;
}


Is it possible to return data with async:true because I can't show any ajax-loader image asyn:false

Answer

No it's not possible. You can't return responseText from async call. Because initAjax will end it's exection, before ajax will get something from server.

A common way to get around of this is to return Promise, and wait when it will be resolved.

var initAjax = function (){
  var customAjaxResponse = $.ajax({
        type: 'POST',
        url: url,
        data: data,
        beforeSend: function (xhr) {
            $(".preloader div").removeClass('hide');
        }
    }).done(function (jsondata) {
        //done
    }).error(function (jqXHR, exception) {
        //error
    });
   return customAjaxResponse.promise();
}
var promised_data = initAjax();
promised_data.then( function( response ){
   //code to process response
} );

Also try to look to promise library's: Q, Bluebird ...

Library's Comparison

Another way to solve your issue is to use Babel's async/await. But, as far as I know, this syntax isn't part of es6 or es7.

Comments