Tariq
Tariq

Reputation: 155

How to load image spinner while getting data in Ajax

I got a great response from this site. now my final thing is show gif loading image while getting data in Ajax..

my code is :

function vote(id)
{ 

    var result = new Array();
    document.getElementById('sub-cat').innerHTML = ajax_image; 
     result = $.ajax({
                       type: "POST",
                       url: "ajax.php",
                       data: "id="+id,
                       async: false
               }).responseText.split("^");
document.getElementById('sub-cat').innerHTML = result[0];
document.getElementById('sub-cat1').innerHTML = result[1];


//window.location.reload()
}

i have tried below code but no work... :(

function vote(id)
{ 
    var ajax_image = "<img src='_assets/images/tire-loader.gif' alt='Loading...' />";

    var result = new Array();
     //$('#sub-cat').html(ajax_image);
    document.getElementById('sub-cat').innerHTML = ajax_image; 
     result = $.ajax({
                       type: "POST",
                       url: "ajax.php",
                       data: "id="+id,
                       async: false
               }).responseText.split("^");
document.getElementById('sub-cat').innerHTML = result[0];
document.getElementById('sub-cat1').innerHTML = result[1];


//window.location.reload()
}

Really appreciate your hard work

Upvotes: 0

Views: 368

Answers (1)

Kuldeep
Kuldeep

Reputation: 884

There are some callbacks in ajax request, beforeSend,success,complete,error etc... So you just have you show the image in beforeSend callback and hide it in complete callback.
$.ajax({
       type: "POST",
       url: "ajax.php",
       data: "id="+id,
       async: false,
       beforeSend: function(){
         document.getElementById('sub-cat').innerHTML = ajax_image;
       },
       complete: function(){
         document.getElementById('sub-cat').innerHTML = "";
       }
          }).responseText.split("^");
    document.getElementById('sub-cat').innerHTML = result[0];
    document.getElementById('sub-cat1').innerHTML = result[1];

    });

Upvotes: 1

Related Questions