Loading with Ajax

0

I wanted to know how to make an image, or something, to indicate that the page is loading. I have a process that takes about 7 seconds and for the user not to click on thinking it was not, I would like to display a loading image or something. Here's part of my code

<a onclick="Open('/CMS/Pedido/Index');" href="javascript:void(null);">Ver Pedidos</a>

I tried to add an image to the div but it did not work:

 <script>
    function Open(url) {
        var img = $("<img />").attr('src', '~/Content/Images/loading.gif'); 
        $("#Conteudo").clear().append(img);

        $("#Conteudo").load(url);
    }
</script>
    
asked by anonymous 12.06.2014 / 18:50

2 answers

1

The .load() of jQuery is limited. Let's replace your $('#Conteudo').load(url) so $.ajax() :

$.ajax({
    url: url,
    beforeSend: function () {
        $('body').append('<div class="loader">Carregando. Aguarde, por favor.</div>');
    },
    success: function (response) {
        $('#Conteudo').html(response);
        $('.loader').remove();
    }
});

beforeSend of $.ajax will execute something you want so that you send the request - in this case, type GET to url . The success is the trigger if your request arrives at your destination, also in case , url .

So when we issue the request, we load the loader. When it is answered successfully - probably after the 7 seconds that are occurring - we have deleted the loader from the screen.

Basically that's it. Implementations are on your own.

    
12.06.2014 / 19:03
1

You could start loading by the time the Open() function was fired, and close it as soon as the AJAX response returned. Example:

function Open(url){
    //Chama o loader
    loaderInit();

    //Faz a requisição AJAX
    $.get(url,function(response){
        // Assim que algo retornar, fecha o loader
        loaderClose();
        // E popula o elemento #conteudo com o que foi retornado
        $('#conteudo').html(response);
    });
}

function loaderInit(){
    // Se não tiver nenhum loader no DOM
    if($('#loader').length < 1){
        // Cria o loader
        $('body').append('<div id="loader"></div>');
    }
}

function loaderClose(){
    // Remove o loader do DOM
    $('#loader').remove();
}
    
12.06.2014 / 19:32