[jquery] Jquery Ajax Loading image

I would like to implement a loading image for my jquery ajax code (this is when the jquery is still processing) below is my code:

$.ajax({
    type: "GET",
    url: surl,
    dataType: "jsonp",
    cache : false,
    jsonp : "onJSONPLoad",
    jsonpCallback: "newarticlescallback",
    crossDomain: "true",
    success: function(response) {
        alert("Success");
    },
    error: function (xhr, status) { 
        alert('Unknown error ' + status);
    }   
});

How can I implement a loading image in this code. Thanks

This question is related to jquery ajax

The answer is


Its a bit late but if you don't want to use a div specifically, I usually do it like this...

var ajax_image = "<img src='/images/Loading.gif' alt='Loading...' />";
$('#ReplaceDiv').html(ajax_image);

ReplaceDiv is the div that the Ajax inserts too. So when it arrives, the image is replaced.


Description

You should do this using jQuery.ajaxStart and jQuery.ajaxStop.

  1. Create a div with your image
  2. Make it visible in jQuery.ajaxStart
  3. Hide it in jQuery.ajaxStop

Sample

<div id="loading" style="display:none">Your Image</div>

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
    $(function () {
        var loading = $("#loading");
        $(document).ajaxStart(function () {
            loading.show();
        });

        $(document).ajaxStop(function () {
            loading.hide();
        });

        $("#startAjaxRequest").click(function () {
            $.ajax({
                url: "http://www.google.com",
                // ... 
            });
        });
    });
</script>

<button id="startAjaxRequest">Start</button>

More Information


Please note that: ajaxStart / ajaxStop is not working for ajax jsonp request (ajax json request is ok)

I am using jquery 1.7.2 while writing this.

here is one of the reference I found: http://bugs.jquery.com/ticket/8338