user2997418 user2997418 - 2 months ago 8
Javascript Question

.ajaxStart and .ajaxStop don't work

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"] ?>');
}
});

Answer

Try ajaxStart and ajaxStop

$(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"] ?>');
        }
    });
}