Message from "Loading ..." with jQuery.post (ajax)

1

I am using this type of data sending through jQuery.post, where do I place a loading image ... or a message while the function returns something?

$.post( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
});
    
asked by Drago25 02.03.2016 в 00:52
source

2 answers

5

The trick is to use ajaxStart and ajaxStop .

These events are invoked by jQuery every time an ajax request starts / ends. Either they are made by the methods post , ajax , load , ..

It is very useful because if there are several ajax requests in parallel, the ajaxStop event is invoked when the last request ends. And the ajaxStart event is not repeated if there is already a request in progress.

$(function() {

  // tu elemento que quieres activar.
  var cargando = $("#cargando");

  // evento ajax start
  $(document).ajaxStart(function() {
    cargando.show();
  });

  // evento ajax stop
  $(document).ajaxStop(function() {
    cargando.hide();
  });

  // cualquier llamada ajax
  $.post("ajax/test.html", function(data) {
    $(".result").html(data);
  });
});
    
answered by 02.03.2016 / 00:57
source
1

In the script that you propose the function is a callback and it is executed when an event happens (in this case the post ends), as you want to do at that moment it is enough to act outside the callback.

$.post("ajax/test.html", function(data) {
  $(".result").html(data); // esto se ejecuta cuando el post termine
});
$(".result").html('loading'); // esto se ejecuta después de hacer el post

If what you need is to do this for any AJAX the answer of @rnd is better.

    
answered by 02.03.2016 в 01:03