Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display 'loading' image when AJAX call is in progress

I have the following jQuery Ajax call:

$.ajax({
                   type: "POST",
                   url: "addtobasket.php",
                   data: "sid=<?= $sid ?>&itemid=" + itemid + "&boxsize=" + boxsize + "&ext=" + extraval,
                   success: function(msg){
                     $.post("preorderbasket.php", { sid: "<?= $sid ?>", type: "pre" },
                     function(data){
                        $('.preorder').empty();
                         $('.preorder').append(data); 
                     }); 
                   }
                 });

I want to display an image when the ajax call is in progress. How can I do that?

Thanks,

like image 936
Or Weinberger Avatar asked Aug 16 '11 17:08

Or Weinberger


3 Answers

Something along these lines (showLoadingImage and hideLoadingImage are up to you):

// show the loading image before calling ajax.
showLoadingImage();

$.ajax({
    // url, type, etc. go here
    success: function() {
        // handle success. this only fires if the call was successful.
    },
    error: function() {
        // handle error. this only fires if the call was unsuccessful.
    },
    complete: function() {
        // no matter the result, complete will fire, so it's a good place
        // to do the non-conditional stuff, like hiding a loading image.

        hideLoadingImage();
    }
});
like image 33
Lobstrosity Avatar answered Oct 12 '22 15:10

Lobstrosity


try this :

<script type="text/javascript">
    $(document).ready(function()
    {
        $('#loading')
            .hide()
            .ajaxStart(function() {
                $(this).show();
            })
            .ajaxStop(function() {
                $(this).hide();
            });
    });
</script>

<div id="loading">
        Loading....
</div>

This will show the loading image each time you are doing an ajax request, I have implented this div at the top of my pages, so it does not obstruct with the page, but you can always see when an ajax call is going on.

like image 103
DonSeba Avatar answered Oct 12 '22 16:10

DonSeba


You can display the image just before this call to $.ajax() and then hide/remove the image in the post handler function (just before your .empty()/.append(data) calls.

like image 22
jeremyasnyder Avatar answered Oct 12 '22 16:10

jeremyasnyder