I have a scroll-to-load-content function, where
//s > selector which define the number of Sql results given by results.php?selector=s
jQuery.fn.ShowResults = function(t,s){
var loading = false; //to prevents multipal ajax loads
var track_load=0;
var total_groups=t;
$("#results").load("results.php?selector="+s, {'group_no':track_load},
function() { track_load++; });
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height())
{
if(track_load <= (total_groups-1) && loading==false)
/*I think that in this line is the clue*/
{
loading = true;
$.post("results.php?selector="+s, {'group_no':track_load}, function() {
$('#results').append(data);
track_load++;
loading = false;
});
}
}
}
}
$("#results").ShowResults(8,1);
$("#show1").on("click", function(e){ $("#results").ShowResults(8,1);});
$("#show2").on("click", function(e){ $("#results").ShowResults(6,2);});
$("#show3").on("click", function(e){ $("#results").ShowResults(4,3);});
I have by default selector=1
;
<a id=show1>Show 1</a>
<a id=show2>Show 2</a>
<a id=show3>Show 3</a>
<ul id=results></ul>
PHP results.php?selector=1
would be
if($_POST)
{
$data_per_group=10; //each group return 10 records as maximun
$group_number = $_POST["group_no"];
$position = ($group_number * $data_per_group);
$s=$_GET['selector'];
if($s==1){$results=mysql_query("SELECT * WHERE condition1 LIMIT $position, $data_per_group");}
if($s==2){$results=mysql_query("SELECT * WHERE condition2 LIMIT $position, $data_per_group");}
if($s==3){$results=mysql_query("SELECT * WHERE condition3 LIMIT $position, $data_per_group");}
while($res=mysql_fetch_array($results)){
$data=$res['names'];
echo "<li>$data</li>";
}
}
the problem is that sometimes, it looks like the function is called twice, and shows the same results repeated like this
<ul id=results>
<li>AAA</li>
<li>BBB</li>
<li>CCC</li>
<li>AAA</li>
<li>BBB</li>
<li>CCC</li>
</ul>
I have tried to use event.preventDefault();
and event.stopPropagation();
with no solution
The question is how do I stop this function behaviour? It looks like that anytime I click the anchors, I call twice the same function and conflicts with the set by default. I was adviced to us mysql_fetch_row()
but the problem is still on. update. After testing many times, I realize That it shows twice becouse of the scroll. I need to improve this lines if(track_load <= (total_groups-1) && loading==false)
or maybe anytime I click an anchor the function takes the number of groups total_groups
from the default release.