0

I am using the latest version of jQuery

i want to display ajax-load/progress image while jquery doing the request and after request complete i want to hide that.

So i may hide that on .success event, but on which event i may display that?

 $.ajax({ url: "example.php" })

     //where to display progress?

    .success(function() {  //hide progress })
    .error(function() { //hide progress })
    .complete(function() {  //hide progress });

2 Answers 2

3

You can display progress just before the ajax call.

 // display progress

 $.ajax({ url: "example.php" })

     //where to display progress?

    .success(function() {  //hide progress })
    .error(function() { //hide progress })
    .complete(function() {  //hide progress });

Or you can register it in ajaxStart:

$('.log').ajaxStart(function() {
  // display progress
});

This way, anytime some ajax call begins, you don't have to manually display progress. Extending that, you can hide that automatically too using ajaxStop or ajaxComplete:

$('.log').ajaxStop(function() {
  // hide progress
});
Sign up to request clarification or add additional context in comments.

4 Comments

so yes, but there is no such event like beforeRequest or something?
I use ajax alot and never heard of .ajaxStart and .ajaxStop. They are quite useful. does this only need to be called once in document.ready?
@Johnny: Yes. You need to set them up only once.
It could be the element (div e.g.) that display progress.
1

Do it before you make the AJAX request:

function MakeRequest() {
    $('#progress').show();
    $.ajax(...)
        .success(function() { $('#progress').hide(); })
        .error(function() { $('#progress').hide(); })
        .complete(function() { $('#progress').hide(); });
}

If you're looking to actually report progress (10%, 20%, etc.) then you will have to rethink this, as this setup will take you from 0 to 100 with no real "progress" getting reported at all. This type of setup is fine for a spinner or a loading message, but that's about it.

Looking through the jQuery docs, there is a beforeSend event that is local to the request. You can use it like so:

 $.ajax({
   beforeSend: function(){
     // Handle the beforeSend event
     // Show progress
   },
   complete: function(){
     // Handle the complete event
     // Hide progress
   }
   // ......
 });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.