I want to show a div that serves as a loading screen when invoking an Ajax update from a click handler that can take a second or two, something like:
var loadingControl;
loadingControl = $("#loading"); // Is initialized after DOM Ready
$('#updateLink').click(function (e) {
loadingControl.show();
$.ajax(
{
url: 'http://some.url',
type: "POST",
success: function (data) {
$('#divToUpdate').html(data);
},
error: handleAjaxError
});
loadingControl.hide();
e.preventDefault();
});
The loading div does not show. I suspect that is because the DOM does not update until the click handler completes. Is that correct?
How can I restructure this code to allow the DOM to update after the call to .show(), so that the loading screen div is visible while .ajax is running?
The ajax call is asynchronous, so the code continues to run. Therefore your
loadingControl.hide()function is getting called right after the ajax starts, try moving yourloadingControl.hide();inside thesuccessfunction.