开发者

display an ajax loader icon when submitting a form

开发者 https://www.devze.com 2023-03-27 23:23 出处:网络
My need is very simple. When a user try to log in and submit the login form, i would to display an ajax loader icon (like ones generated at www.ajaxload.info) in foreground with the background transpa

My need is very simple. When a user try to log in and submit the login form, i would to display an ajax loader icon (like ones generated at www.ajaxload.info) in foreground with the background transparent and unclickable (like in this site). when the server has f开发者_如何学Cinished, it can display the next page or redisplay the old one with the errors.

How can i do that?

Thank you very much in advance.


Using jQuery (which is a great javascript library and has hundreds of uses besides this one) you can detect the submit event on the form and take some action, like this:

$(function(){  
 $('#yourFormId').on('submit', function(e){
        //stop the form refreshing the page
        e.preventDefault();

        //serialize the form for submission to the server
        var data = $(this).serialize();
        //get the url for the form
        var url = $(this).attr('action');

        //make an ajax request to submit the form, showing the loader and unclickable div
        $('#yourAjaxLoader,#unclickableDiv').fadeIn();
        $.post(url, data, function(response){
            //the request has completed, so fade out the loader and div
            $('#yourAjaxLoader,#unclickableDiv').fadeOut();
        });  
    }); 
});

To acheive the unclickable div, try some css like this:

/*css*/    
#unclickableDiv
{
    z-index:99999;
    width: 100%;
    height: 100%;
    opacity: 0.5;
    background-color: black;
    display:none;
}

and put the div just inside the body tag. when it is faded in, it will be 'above' the rest of the page, making it unclickable. just put your ajax loading icon inside this div so it will show up, too.

You can get jQuery from http://jquery.com and I highly recommend using it anyway, even if not for this. Hope this helps

Update:

The new jQuery on() method has effectively replaced .submit and .click etc since version 1.7, so I've updated this example to reflect that. More info here: http://api.jquery.com/on/


You could use JQuery and take a look at Throbber plugin (http://plugins.jquery.com/plugin-tags/throbber):

Provides trivially easy way to notify users that a request is being loaded and processed in the background, so that they know their action was received and the page has not frozen. Just toggle the message (or image or any element) on or off with $.loading() or $('#foo').loading(). The plugin handles creation and positioning and "pulsing" of the message for you. It also provides a 'mask' option to block the UI (at the call level) while the loading message (or image or any element) is running.

0

精彩评论

暂无评论...
验证码 换一张
取 消