ajsie
ajsie

Reputation: 79836

easiest way to show "loading" when using jquery ajax?

I want to know the easiest way of showing a 'loading' gif to a specific jquery ajax request.

i have tried:

$(document).ajaxStart(function() {
    $('.hideOnLoad').hide();
});
$(document).ajaxStop(function() {
    $('.hideOnLoad').show();
});

but then ALL ajax requests will trigger it. i just want a specific jquery ajax request to trigger the loading process (maybe a gif will be shown).

how do i do that?

Upvotes: 3

Views: 765

Answers (5)

AndyFlan
AndyFlan

Reputation: 11

I tend to do something along the lines of:

$('#some-div').addClass('loading');

when I begin and

$('#some-div').removeClass('loading');

when I'm done. Then I have

#some-div { 
    background: transparent url('ajazz-loader.gif') no-repeat center center; 
}

in my css. Nice and clean.

Upvotes: 0

Teja Kantamneni
Teja Kantamneni

Reputation: 17482

In beforeSend callback you have to show the spinner and in complete you have to hide it. Just FYI: ajaxStart and ajaxStop are global ajax events while beforeSend and complete are local.

Upvotes: 7

Pointy
Pointy

Reputation: 414006

Just show the image before you start the ajax call, and then in your ajax "success" or "complete" handler, hide it.

Upvotes: 1

Carlos Blanco
Carlos Blanco

Reputation: 8772

Set container's content to the gif image. Then do the Ajax call. The gif image will be removed by the Ajax callback function.

Upvotes: 0

sberry
sberry

Reputation: 132138

I usually do something like

$('#someTrigger').click( function(el) {
    // do my ajax request with callback, onComplete
    $('.someImageClass').show();
});

function onComplete(resp, respText, XMLHttpRequset) {
    // do stuff
    $('.someImageClass').hide();
}

Upvotes: 1

Related Questions