0

I have page that displays data through AJAX, till the time the result is being fetched I wish to display a loader and as soon as the result is fetched I want that the loader should disappear. Below is part of the code where I am trying to display the loader

var onSubmit = function(e) 
    {
        var txtbox = $('#txt').val();
        var hiddenTxt = $('#hidden').val();

        $("#walkaway").hide();
        $("#submitamt").hide();
        $("#xtrabutton").hide();

        LodingAnimate();
        $.ajax(
            {
                type: 'post',
                url: 'test2.php',
                dataType: 'json',   
                data: {txt: txtbox,hidden: hiddenTxt},
                cache: false,
                success: function(returndata) 
                    {
                        $('#first').html(returndata[0]);
                        $('#second').html(returndata[0]);
                        $('#third').html(returndata[0]);
                    },
                error: function() 
                    { 
                        console.error('Failed to process ajax !');
                    }
            });

            function LodingAnimate() 
            {
                $("#maillist").html('<img src="img/ajax-loader.gif" /> Please Wait Loading...');
            }   
    }; 

On click of a button the above AJAX is executed, after the click the loader runs but even after I get the reply(in console) the loader keeps on running, but in actual it should have disappeared.

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

3

You should hide/remove the loader manually after ajax call completes, add Jquery Complete call back and add the code to remove the loader in it.

Jquery Complete - This call back will execute after success and error call back executed.

     $.ajax(
            {
                type: 'post',
                url: 'test2.php',
                dataType: 'json',   
                data: {txt: txtbox,hidden: hiddenTxt},
                cache: false,
                success: function(returndata) 
                    {
                      //Success code
                    },
                error: function() 
                    { 
                        //error code
                    },
                complete:function()
                    {
                     //This block will execute after success/error executes.
                     //Make the loader div empty
                     $("#maillist").empty();
                    }
            });
ssilas777
  • 9,672
  • 4
  • 45
  • 68