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 );
});
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 );
});
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);
});
});
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.