Loading with Ajax

Asked

Viewed 1,336 times

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 keep clicking thinking it was not, I would like to display a loading image or something. Follow 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 didn’t go very well:

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

        $("#Conteudo").load(url);
    }
</script>
  • http://answall.com/questions/12181/system_loadprogression_site/12187#12187 , now. You have a solution to this question

2 answers

1


The .load() jQuery is limited. We will replace your $('#Conteudo').load(url) therefore $.ajax():

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

The beforeSend of $.ajax will execute something you want as soon as you submit the request - in this case, type GET for url. The success is the coupler if your request arrives at your destination, also in the case of, url.

So when we fire the requisition, we load the scanner. When it is successfully answered - probably after the 7 seconds that are occurring - we delete the Upload from the screen.

That’s basically it. Implementations are on their own.

1

You could start the loading at the time when the function Open() 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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.