RandomUser RandomUser - 2 months ago 7
Ajax Question

Element not shown before jQuery ajax call

I have an ajax loader gif that should be shown before the ajax call is triggered and hidden on ajax complete, however the element is not showing up.

If I debug using inspect and run step by step the element is shown.

$("#ajaxLoader").show();
$('.spn-invalid-zip').hide();
$("#txtZipCode").removeClass("input-validation-error-style");
if ($("#inValidZipCode").length <= 0) {
$($('#txtZipCode').parent()).append("<span id='inValidZipCode' class='spn-invalid-zip input-validation-error-style'></span>");
}
var valZipCode = value;
if (valZipCode.length < 5) {
resetCountyFields();
return false;
}
var zipCodeResult = false;
$.ajax({
url: path,
type: "POST",
data: { zipcode: valZipCode },
async: false,
success: function (data) {
....
},
complete: function () {
$("#ajaxLoader").hide();
}
});

Answer

The issue is because you use async: false in your AJAX call. This blocks the UI thread of the browser from updating while the request is in transit, and hence the imagery you show/hide is never updated on the user's screen. If you remove that property from your AJAX options, your code will work fine:

$("#ajaxLoader").show();

// your logic here:

$.ajax({
    url: path,
    type: "POST",
    data: { zipcode: valZipCode },
    success: function (data) {
        ....
    },
    complete: function () {
        $("#ajaxLoader").hide();
    }
});

Setting the async property to false is used to make the request synchronous, so that you don't need to use callback functions to retrieve the data in the request and so that the UI will not update until the request ends. It's really bad practice though, and the console will warn you about its use as the browser will appear to the user that it has hung until the request complete, which could be several seconds of inactivity.

It's only valid for use in certain situations where code has to complete before the UI updates, onbeforeunload for example. Other than that you should never ever use it.