Tool
Tool

Reputation: 12488

"loading image" between start and end of a ajax request

I want to add a loading image that will be visible between the start and end of an ajax request in jquery.

Currently, when the button I want to replace with a loading image is clicked, this function is called:

function test(num)
{
             $("div.bd_img").attr("style", "display:none");
             $("div.ajax_load").attr("style", "display:block");
             str = "ajax?id=" + num.toString();

             $.ajax({
                type: "GET",
                url: str,
                dataType: "xml",
                success: test2
             });
             $("div.bd_img").attr("style", "display:block");
             $("div.ajax_load").attr("style", "display:none");

}

But it doesnt seem to be working.

The two divisions bd_img and ajax_load are childs of a div, so one should be replaced by another when display is set to none and vice versa.

Upvotes: 0

Views: 1557

Answers (4)

Yasen Zhelev
Yasen Zhelev

Reputation: 4045

I would use ajaxStart and ajaxStop This will make it work for your entire application, keep the code in one place, easy to be modified, etc.

Upvotes: 1

bdparrish
bdparrish

Reputation: 2764

check your test2 method. I would also move your image switch into your success callback.

success: function() {
    $("div.bd_img").show();
    $("div.ajax_load").hide();

    test2();
}

check to make sure your div actually has the class bd_img and ajax_load and that class is not on the actual image. right now you are saying that your div has the class '.bd_img' or '.ajax_load'. if it is an image inside the div with the class, then you want ...

$("div .bd_img").show();
$("div .ajax_load").hide();

Upvotes: 2

6502
6502

Reputation: 114481

You should switch back the images inside test2. Ajax calls area asynchronous so $.ajax(...) returns immediately, not when the request is completed.

Ever wondered what the A of ajax stands for ? :-)

Upvotes: 1

Town
Town

Reputation: 14906

Disable the loader in the callback function (test2 in your case)

Ajax calls by definition are asynchronous. Your current code will fire off the ajax GET and then carry straight on to disable your loader. If you disable the loader in the callback from the ajax call you should see the behaviour you expect.

Upvotes: 3

Related Questions