views:

1118

answers:

2

I'm interested in providing a general "I'm making an ajax call" notification ... similar to how most of google's services have a little red loading notification when it's busy making a call. Is there a way of globally tapping into some event that I can use to show/hide that notification if there is an active call?

We're not using the jQuery ajax apis, we're using the MVC Ajax stuff ... such as Ajax.BeginForm, or Ajax.ActionLink.

+5  A: 

If you are using JQuery to make AJAX calls you can use something among the lines:

jQuery.ajax({
    url: 'url_to_send_ajax_request_to',
    beforeSend: function(XMLHttpRequest) {
        jQuery('#id_of_some_div_that_contains_loading_text').show();
    },    
    complete: function(XMLHttpRequest, textStatus) {
        jQuery('#id_of_some_div_that_contains_loading_text').hide();
    }
});

The beforeSend handler can be used to show a hidden div containing your loading text or image while complete handler will be used to hide it (no matter whether the call succeeds or not).

Or if you want to set it up globally for all AJAX requests you can use the ajaxSetup function:

jQuery.ajaxSetup({
    beforeSend: function(XMLHttpRequest) {
        jQuery('#id_of_some_div_that_contains_loading_text').show();
    },    
    complete: function(XMLHttpRequest, textStatus) {
        jQuery('#id_of_some_div_that_contains_loading_text').hide();
    }
});
Darin Dimitrov
We use the jQuery ajax in just one instance ... all the other functionalities are using the MVC ajax libs. For example Ajax.BeginForm( ...
Joel Martinez
I don't know much about AJAX but shouldn't "XMLHttpReques" have a "t" on the end? It seems you have it without a "t" in both of the "beforeSend" attributes you have specified.
Wayne Koorts
Why is this answer accepted when the question says "We're not using the jQuery ajax apis"?
bzlm
+4  A: 

I'm not sure why the previous answer was accepted, but you can just use the LoadingElementId parameter in your AjaxOptions, by specifying an ID of an element in your page which has its display CSS property set to none.

new AjaxOptions { UpdateTargetId = "somebox", LoadingElementId = "status-waiting" }

MVC will do the rest of the work for you: when the request initiates, the DIV will be shown, and once it completes - hidden again. All you have to do is style the box (position it, provide 'loading' image, etc.).

dalbaeb
It was accepted because you hadn't written this answer yet ;-) thanks!
Joel Martinez
+1 exactly what I was looking for.
James