Reputation:
I have a loading gif that I want to display and hide before and after Ajax request using ajaxStart and ajaxStop. Nothing works:
HTML:
<div id="loading" style="display: none"><img src="loading.gif></div>
JS:
$("#searchForm").submit(function(event)
{
$.ajaxStart(function() {
$( "#loading" ).show();
});
$.ajaxStop(function() {
$( "#loading" ).hide();
});
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
data: $("#searchForm").serialize(), //add the data to the form
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
},
error: function()
{
$('#itemContainer').html('<i class="icon-heart-broken"> <?= $lang["NO_DATA"] ?>');
}
});
Upvotes: 0
Views: 2238
Reputation: 6628
$(document).ajaxStart(function() {
$( "#loading" ).show();
});
$(document).ajaxStop(function() {
$( "#loading" ).hide();
});
There is problem in your HTML also ("loading.gif")
<div id="loading" style="display: none"><img src="loading.gif"></div>
Add event.preventDefault();
in your submit function, that will prevent a submit button from submitting a form.
Or Other way is to do the things in your function only, without calling global functions of ajax.
$("#searchForm").submit(function(event)
{
event.preventDefault();
$( "#loading" ).show();
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
data: $("#searchForm").serialize(), //add the data to the form
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
},
complete: function(){
$('#loading').hide();
},
error: function()
{
$('#itemContainer').html('<i class="icon-heart-broken"> <?= $lang["NO_DATA"] ?>');
}
});
}
Upvotes: 3
Reputation: 2843
$(document).ajaxStart(function() {
$("#gif-image-id").show();
}).ajaxStop(function(){
$("#gif-image-id").hide();
});
Put this as a separate event (outside the submit event), and change the selector to what ever the image id actually is.
Upvotes: 0