Loading on ajax

2

How do I add a loading, to my ajax? This loading would begin when ajax was started and finished when it returned the result. my code:

$.ajax({
    url: url + "login/ajaxLogin",
    type: "POST",
    data: $('#login_form').serialize(),
    success: function(result) {
        alert(result)
    }
});

return false;
    
asked by anonymous 20.07.2015 / 21:00

3 answers

3

First choose a gif of your liking: this site has some very good: link

Now, let's set up:

Place the modal in HTML (this is the element that will appear on the screen with "loading ..."):

<div class="modal"></div>

Let's apply the modal styles in CSS

.modal {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 ) 
                url('http://i.stack.imgur.com/FhHRx.gif') 
                50% 50% 
                no-repeat;
}

/* enquanto estiver carregando, o scroll da página estará desativado */
body.loading {
    overflow: hidden;   
}

/* a partir do momento em que o body estiver com a classe loading,  o modal aparecerá */
body.loading .modal {
    display: block;
}

And in JQuery you use it this way:

$body = $("body");

$(document).on({
    ajaxStart: function() { $body.addClass("loading");    },
     ajaxStop: function() { $body.removeClass("loading"); }    
});

or in your case:

    $body.addClass("loading");
    $.ajax({
        url: url + "login/ajaxLogin",
        type: "POST",
        data: $('#login_form').serialize(),
        success: function(result) {
            $body.removeClass("loading");
            alert(result);
        }
    });

return false;

Source: link

    
20.07.2015 / 21:13
1

You can use this:

$(document).on({

        ajaxStart: function () {                                
            $("#ComponenteLoading").show();                                   
        },
        ajaxStop: function() {

            $("#ComponenteLoading").hide();                    
        }

    });

However, depending on the browser (Google chrome, for example) the parallelism does not work very well in this situation, and if you use synchronous ajax requests, your 'balloon loading' will not be displayed.

The event will be triggered together with the start of the request and the browser will 'hang' and not show the balloon correctly.

In order to work in the situation it is a synchronous ajax request , in these particular browsers, you will have to manually intercept the correct point of show / hide balloon:

$("#ComponenteLoading").show();
$.post("/UrlServico/Teste", function(dados){
        $("#ComponenteLoading").hide();
});
    
20.07.2015 / 21:08
0

I think this code will help you.

$(document).ajaxStart(function (){
    //Show loading
}).ajaxStop(function () {
    //Hide loading
})
    
20.07.2015 / 21:11