Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Ajax loading image while getting the data

Tags:

jquery

ajax

I am using a Jquery Ajax function to fetch the data from database, on click event.

This function works fine and displays the data. But it takes time to load the data, so I want to put a loading image, while the data is been fetched. I used this method to do

<script type="text/javascript">
    jQuery(function($) {
        $(document).ready(function() {
            $("#imgs").hide();
            $(".letter").bind('click', function(){
                $("#imgs").fadeIn();
                var val = $(".letter").val;
                var site = '<?php echo site_url(); ?>';
                $.ajax({
                    url: site+'/wp-content/themes/premiumnews/newContent.php?letter='+$(this).html(), 
                    success:function(data){
                        $("#imgs").hide();
                        $("#content1").html(data);
                    }
                });
            });
        });
    });
</script>

When I click on the button, the loading image appears, but after success the image should disappear, in my case it still remains there

Is my code wrong? or I have used a wrong method?

like image 886
Niraj Chauhan Avatar asked Feb 22 '26 10:02

Niraj Chauhan


2 Answers

This is what I have always used in the past:

$('#loading_div').hide().ajaxStart(function(){
    $(this).show();
}).ajaxStop(function() {
    $(this).hide();
});
like image 60
Phil Avatar answered Feb 24 '26 12:02

Phil


Just before your $.ajax(); call do this. Replace the entire html with this before the ajax call. Then onsuccess the entire html is replaced with your content.

$("#content1").html("<img style=\"margin-left: auto; margin-right: auto;\" src=\"ajax-loader.gif\" alt=\"Loading...\" title=\"Loading...\" />");
like image 20
Caimen Avatar answered Feb 24 '26 12:02

Caimen