Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display an ajax loader icon when submitting a form

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 finished, 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.

like image 477
rico Avatar asked Aug 15 '11 12:08

rico


1 Answers

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/

like image 69
totallyNotLizards Avatar answered Sep 23 '22 15:09

totallyNotLizards