Merbin Jo Merbin Jo - 2 months ago 7
Javascript Question

jQuery ajax not show and hide the loader div

I am calling php code using jquery ajax function, but I wan to show a loader div while sending the request and after complete the request hide the div.For testing purpose just I hold the php execution 5seconds using sleep(5) method, show should I can see this loader. It is not working for me I had try the following code

First Try

show_loader();
$.ajax(
{
async: false,
url: "bindanswerposts.php",
data: "sessuserid="+sessuserid+"&postid=" + _ViewPostid + "&xcode=" + $("body").data("xcode"),
type: "POST",

success: function(resp)
{
hideloader();
},
error: function(e)
{
hideloader();
}
});


Second Try

$(document).ajaxStart(function(){
showloader();
});

$(document).ajaxComplete(function(){
hideloader();
});

$.ajax(
{
async: false,
url: "bindanswerposts.php",
data: "sessuserid="+sessuserid+"&postid=" + _ViewPostid + "&xcode=" + $("body").data("xcode"),
type: "POST",

success: function(resp)
{

},
error: function(e)
{

}
});


Third Try

$.ajax(
{
async: false,
url: "bindanswerposts.php",
data: "sessuserid="+sessuserid+"&postid=" + _ViewPostid + "&xcode=" + $("body").data("xcode"),
type: "POST",
beforeSend: function() {
showloader();
},
complete: function() {
hidloader();
},
success: function(resp)
{

},
error: function(e)
{

}
});


But every above methods are not worked, please help me. But in normal javascript ajaxRequest is working fine.

ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 1)
{
showloader();
}

if(ajaxRequest.readyState == 4)
{
hideloader();
}
}

Answer

Try to use complete method of ajax.

Make sure that you've loader in your DOME.

<div id="loading" style="display: none"><img src="loading.gif"></div>

Ajax call

//Show loader here
$( "#loading" ).show();
$.ajax({
       //async: false,
       url: "bindanswerposts.php",
       data: "sessuserid="+sessuserid+"&postid=" + _ViewPostid + "&xcode=" + $("body").data("xcode"),
       type: "POST",
       success: function(resp)
       {

       },
       error: function(e)
       {        

       },
       complete:function()
       {
          //Hide the loader over here
          $('#loading').hide();
       }
});

EDIT Remove async=false, it should work.

  • For synchronous ajax call, it does NOT. Ajax gets executed first and all other processes are blocked/queued.