Load Ajax data while scrolling a page using PHP

To load data while scrolling through a page using a function like this

$(window).scroll(function(){ if ($(window).scrollTop() == $(document).height() - $(window).height()) { //alert('Scrolling Down'); get_summary_details(); //Here it calls AJax Function load the data } }); 
Function

get_summary_details() works fine when the page scrolls down. This function is similar to this.

 function get_summary_details() { var dataString=[]; $('div.company_summary_data').each(function() { var id = $(this).attr('id'); dataString.push(id); }); $.ajax({ url:"getajaxcompanysummarydetails", type:"POST", //dataType: "json", data:"last_app_data_id="+JSON.stringify(dataString), success:function(data) { $('.company_summary_data:last').after(data); } }); } 

My problem

  • while get_summary_details() processing the request. The user will go to the top page and Scroll down, this get_summary_details() function will be executed again.

How to prevent this Second request processing without completing the first request. Is it possible? Because of this, I get duplicate data records. I need to prevent the display of duplicate entries.

Thanks!

+5
source share
2 answers

You need to check if the ajax request is busy by setting the boolean flag

 var loadingSummaryDetails = false; 

Set to true when starting Ajax and false when the call completes

 function get_summary_details() { if(loadingSummaryDetails) { return; } loadingSummaryDetails = true; var dataString=[]; $('div.company_summary_data').each(function() { var id = $(this).attr('id'); dataString.push(id); }); $.ajax({ url:"getajaxcompanysummarydetails", type:"POST", //dataType: "json", data:"last_app_data_id="+JSON.stringify(dataString), success:function(data) { $('.company_summary_data:last').after(data); } }).always(function() { loadingSummaryDetails = false; }); } 
+1
source

Your AJAX requests are most likely queuing up for each other because they are asynchronous, although JavaScript itself is mostly single-threaded.

You can use the abort() method to make sure that only one request is run at a time. You need to assign the jqXHR object returned by $.ajax() variable:

see link

+2
source

All Articles