Ovi
Ovi

Reputation: 2559

adding a animated image while jquery ajax is working

I am using Jquery Ajax, my code looks like this

 $.get(
    'GetPage.aspx',
    'url=' + url ,
    function (response) {
        if (!cancelNavigationFlag)
            setIframeHtml(response);
        cancelNavigationFlag = false;
    },
    'html'
);

I need to add a animated gif that will appear while the ajax is working and then disappear when the ajax finishes.

How can i do that?

Upvotes: 0

Views: 1944

Answers (3)

Mahesh KP
Mahesh KP

Reputation: 6446

you can add a div which contains an image tag with loader image. Initially hide the div. Before calling the ajax request show the div. and after getting data from ajax request hide the div.

$("#dvLoader").show();
$.get(
    'GetPage.aspx',
    'url=' + url ,
    function (response) {
        if (!cancelNavigationFlag)
            setIframeHtml(response);
        cancelNavigationFlag = false;
    },
    'html'
    success:
         function(data)
         {
            $("#dvLoader").hide();
         }

);

dvLoader contains an the loader image.

Upvotes: 0

Alfred
Alfred

Reputation: 21396

I have a different logic and solution.

Set a div where you want the gif image to appear like <div id="loader">.

Next, Set it a background image in css and don't set the image link like;

background: no-repeat center;

and when ajax execute, give it a background image loader.gif and remove it when ajax task completes, like;

 $.get(
    $("#loader").css({ 'background-image':'url(images/loader.gif)' });
    'GetPage.aspx',
    'url=' + url ,
    function (response) {
        if (!cancelNavigationFlag)
            setIframeHtml(response);
        cancelNavigationFlag = false;
        $("#loader").css({ 'background-image':'url()' });
    },
    'html'
);

I have not tested it myself.. Hope this helps..

Upvotes: 2

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

I normally do something like this:

$("#indicatordiv").show();
$.post("somepage", function(result){ 
    $("#indicatordiv").hide();
})

Where "indicatordiv" is a simple div element containing the loader gif image.

So in your case, just ".show()" the element before the get request, and ".hide()" it inside the response function.

Upvotes: 1

Related Questions