This question already has an answer here:
How to paginate query results for Infinite Scroll?
(1 answer)
Closed 8 years ago.
Infinite scroll should stop after 10 rows of records. If there are more records, ajax pagination should be displayed. For example, consider this infinite scrolling example.
So after 20 records I want to display pagination and same should be done on next page. Please let me know if you have any of this ideas or solution.
Here is my code on which I am working:
//On doMouseWheel = 1 I have taken the currentdealoffset value and check it with the total no of deals present
//If count is less, then simply calculating the window position displaying the allotted records say 10
//On next scroll just doing the same process and fetching records using ajax until end of the deals
//Now the problem is I am not able to code a logic where after say 10 records show a pagination and
//When click on next page the same process should be managed by fetching the offset count of scrol and offset of pagination bar
doMouseWheel = 1 ;
$(window).scroll(function() {
if($('#facebox_overlay').is(':visible')==false){
$('#endofdeals').show();
$('#endofdeals').html("<center><img src='"+SITEIMG +"ajax-loader_1.gif' ><center>");
//console.log("Window Scroll ----");
var currentdealoffset = 0; //alert(currentdealoffset);
var currentdealoffset = parseInt(document.getElementById("countval").value); //alert(currentdealoffset);
var displaymode = parseInt($('#displaymode').val());
var totalcountdeal = parseInt($('#totaldeals').val()); //alert(totalcountdeal);
if(currentdealoffset<totalcountdeal){
if (!doMouseWheel) {
return ;
} ;
var distanceTop = $('#last').offset().top - $(window).height();
if ($(window).scrollTop() > distanceTop){
//console.log("Window distanceTop to scrollTop Start");
doMouseWheel = 0 ;
$('div#loadMoreComments').show(5000);
//console.log("Another window to the end !!!! "+$(".postedComment:last").attr('id'));
$.ajax({
type : 'POST',
dataType : "html",
data: {
typeday : $('#remdumtype').val(),
catid : $('#catid').val(),
},
url: "<?php echo https_url($this->config->item('base_url'))?>popup/dealsearch",
success: function(html) {
doMouseWheel = 1;
if(html){
if(displaymode==12)
$('#listTable tr:last').after(html);
else
$("#postedComments").append(html);
//console.log("Append html--------- " +$(".postedComment:first").attr('id'));
//console.log("Append html--------- " +$(".postedComment:last").attr('id'));
$("#last").remove();
$("#postedComments").append( "<p id='last'></p>" );
$('div#loadMoreComments').hide();
$('#endofdeals').hide();
}
}
});
}
}
else
{
if($('#endofdeals')!='')
{
$('#endofdeals').hide();
if(currentdealoffset < displaymode)
{
$('#endofdeals').hide();
}else if(currentdealoffset > displaymode)
{
$('#endofdeals').show();
$('#endofdeals').html("<center><h2 style='color:#4C335B'>End of deals !!!!!!!</h2></center>");
}
}
}
}
});
According to me, You want page numbers but the pages should load slowly as you scroll.
If this you want then, you should not use Infinite scroll technique but LazyScroll will help you and if you want 20 records then make your query for 20 records also create pagination below
Here, you can have the Plug-in and Demo.
Related
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.
Simply change track_load from 0 to 1.
The .load() request already gets the first 'track', yet the first $.post request requests track_load 0 again.
I did solve the issue, thanks to everyone who tried to help me.
the problem it was that anytime I click an anchor a, for some reason, the page still keept the prior value of total_groups.
jQuery.fn.ShowResults = function(t,s){
var total_groups=t;
setInterval( function(){alert(total_groups);},2000)
/*more coding*/
}
By default it was set selector=1 $("#results").ShowResults(8,1); .So when I clicked on a id=show2 $("#results").ShowResults(6,2);, it can be seen alerts ,setInterval(), showing different total_groups values, 8 & 6. And if I press a id=show3 $("#results").ShowResults(4,2);, the alert in one moment will display 8,6 & 4. Why this happens I still dont know.
so I decided to add $ajax({}); in order to obtain total_groups from another page total_groups.php?s=selector which returns the total_groups value only.
jQuery.fn.ShowResults = function(s){
$ajax({
type: 'POST',
url: "total_groups.php?s="+selector,
data: $(this).serialize(),
success: function(data) {
var total_groups=data; //I obtain total_groups by ajax now.
$("#results").load();
$(window).scroll(function() {
/*append data code*/
}//end load scroll
}//end success
});//end ajax
}//end function
So by using Ajax, the problem is finally solve.
my apologies if its an incomplete or irrelevant question but I am having a big problem in my code. By using ajax I call a list of hotel rooms using an API. Now I call separate asynchronous ajax requests using JQuery to get cancellation policy of these rooms. The ajax requests are going to single PHP script on the server. If cancellation policy is present then show the book button for the room and if cancellation policy is not present then hide the room.
Now the issue is that suppose there are 5 rooms and one room returns cancellation policy 1st I show its book button which is an anchor tag with href to checkout page. But if I click on this anchor tag the page takes 15-20 seconds more before it goes to the href location.
Kindly let me know what can I do to reduce this time or what can I do to check where my page is spending these 15-20 seconds.
If needed I can provide links to test this module on my staging link.
Thanks.
var xhrRequests = [];
function filterByCancellation(){
$( ".hotel_package_row:visible" ).each(function( index ) {
var cancellation_obj = $(this).find( ".cancellationText" );
var pack_price = 0;
var hotel_price = 0;
if ($(cancellation_obj).text()=="") {
var hotelid = $(cancellation_obj).prev("a").data( "hotelid"),
packid = $(cancellation_obj).prev("a").data( "packid"),
cancel = $(cancellation_obj);
if(!$('#anc-'+packid).is(':visible') && $('#inp-'+packid).val()=="0"){
$('#inp-'+packid).val("1");
cancel.html('').slideToggle(function(){
var data = { hotelid: hotelid, packid: packid };
pack_price = parseInt($('#packprice_'+packid).val());
var xhr = $.ajax({
type: "POST",
url: "location_penny.php?section=cancellationData",
data: data,
success: function(result) {
//cancel.html(result);
if(result.indexOf('<div style="display:none;">') > -1){
$(cancellation_obj).parents('.hotel_package_row').html('');
}else{
hotel_price = parseInt($('#'+hotelid).find('.currency-sign-before').html());
if($("#price_update_"+hotelid).val()=='0'){
//alert("hotel price "+hotel_price+" updating for the first time with package "+pack_price);
$('#'+hotelid).find('.currency-sign-before').html(pack_price);
$("#price_update_"+hotelid).val("1");
}
if(pack_price<=hotel_price){
//alert("hotel price "+hotel_price+" is greater than current package price "+pack_price);
$('#'+hotelid).find('.currency-sign-before').html(pack_price);
}
$('#img-'+packid).hide();
$('#anc-'+packid).show();
}
},
async:true
});
xhrRequests.push(xhr);
});
}
}
});
}
function cancelXhrRequests(){
for (var i = 0; i < xhrRequests.length; i++) {
//xhrRequests[i].abort();
}
}
My question has part solutions on this site but not a complete answer.
On my wordpress homepage I display a counter of the number of questions answered within our webapp. This is displayed using jQuery and AJAX to retrieve the question count from a php file and works fine with this code.
jQuery(document).ready(function() {
function load() {
jQuery.get('/question_count.php', function(data) {jQuery('#p1').html( data ); });
}
load();
setInterval(load,10000);
});
Is there a way to display counting up to the new number retrieved rather than just immediately displaying it?
Something like this?
function countTo(n) {
var p = $("#p1"),
c = parseInt(p.html(), 10) || 0,
dir = (c > n ? -1 : 1); // count up or down?
if (c != n) {
p.html((c + dir) + "");
setTimeout(function() {
countTo(n);
}, 500);
}
}
Call it in your success handler
jQuery.get('/question_count.php', function(data) {
var n = parseInt(data, 10);
countTo(n);
});
Example
You will need to do a setInterval event so that the count up is visable to human eyes.
This may be a problem if you eventually reach enough questions where the count takes a long time to reach the end.
Code will look like this:
function load(){
jQuery.get('/question_count.php', function(data){
var curr = 0;
var max = parseInt(data);
var interval = setInterval(function(){
if(curr==max){
clearInterval(interval);
}
jQuery('#p1').html( curr );
curr+=1; //<-- if the number of questions gets very large, increase this number
},
10 //<-- modify this to change how fast it updates
});
}
}
I am looking for a solution to display many items (10's of thousands) in a list view in Yii. I would like to be able to display them in a continually scrollable list. Here is the catch, when the user scrolls past the end of the list I want the new data to replace the data he just scrolled passed. Kind of like google music if you have a really long play list.
I looked at Yiinfinite-scroller but it appends to the end of the list making a very long list which is killing my memory usage.
Thanks
Its actuality really easy to implement infinite scroll in just a few lines of js and with the help of jQuery. Measure the height of the content div and as the page scrolls subtract the scroll difference from the divs height then when it hit the min amount do the query for more content and reset the height counter and repeat:
<script type="text/javascript">
var contentHeight = 4000,;
var pageHeight = document.documentElement.clientHeight;
var scrollPosition;
var n = 1;
function scroll(){
if(navigator.appName == "Microsoft Internet Explorer")
scrollPosition = document.documentElement.scrollTop;
else
scrollPosition = window.pageYOffset;
if((contentHeight - pageHeight - scrollPosition) < 500){
$.ajax({ url: "./yourAPI/?next="+n, cache: false,
success: function(data){
//append result
$('#infscroll').append('<div>'+data.result+'</div>');
}, dataType: "json"});
n += 1;
contentHeight += 4000;
}
}
$(document).scroll(function(){
setInterval('scroll();', 250);
});
</script>
<div id="infscroll"></div>
I recently came upon a site that has done exactly what I want as far as pagination goes. I have the same basic setup as the site I just found.
I would like to have prev and next links to navigate through my portfolio. Each project would be in a separate file (1.php, 2.php, 3.php, etc.) For example, if I am on the 1.php page and I click "next project" it will take me to 2.php.
The site I am referencing to accomplishes this with javascript. I don't think it's jQuery:
function nextPg(step) {
var str = window.location.href;
if(pNum = str.match(/(\d+)\.php/i)){
pNum = pNum[1] * 1 + step+'';
if ((pNum<1) || (pNum > 20)) { pNum = 1; }
pNum = "".substr(0, 4-pNum.length)+pNum;
window.location = str.replace(/\d+\.php/i, pNum+'.php');
}
}
And then the HTML:
Next Project
I can't really decipher the code above, but I assume the script detects what page you are on and the injects a number into the next page link that is one higher than the current page.
I suppose I could copy this code but it seems like it's not the best solution. Is there a way to do this with php(for people with javascript turned off)? And if not, can this script be converted for use with jQuery?
Also, if it can be done with php, can it be done without dirty URLs?
For example, http://www.example.com/index.php?next=31
I would like to retain link-ability.
I have searched on stackoverflow on this topic. There are many questions about pagination within a page, but none about navigating to another page that I could find.
From your question you know how many pages there are going to be. From this I mean that the content for the pages themselves are hardcoded, and not dynamically loaded from a database.
If this is the approach you're going to take you can take the same course in your javascript: set an array up with the filenames that you will be requesting, and then attach event handlers to your prev/next buttons to cycle through the array. You will also need to keep track of the 'current' page, and check that incrementing/decrementing the current page will not take you out of the bounds of your page array.
My solution below does the loading of the next page via AJAX, and does not change the actual location of the browser. This seems like a better approach to me, but your situation may be different. If so, you can just replace the related AJAX calls with window.location = pages[curPage] statements.
jQuery: (untested)
$(function() {
var pages = [
'1.php',
'2.php',
'3.php'
];
var curPage = 0;
$('.next').bind('click', function() {
curPage++;
if(curPage > pages.length)
curPage = 0;
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
$('.prev').bind('click', function() {
curPage--;
if(curPage < 0)
curPage = (pages.length -1);
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
});
HTML:
<div id = "pageContentContainer">
This is the default content to display upon page load.
</div>
<a class = "prev">Previous</a>
<a class = "next">Next</a>
To migrate this solution to one that does not have the pages themselves hardcoded but instead loaded from an external database, you could simply write a PHP script that outputs a JSON encoded array of the pages, and then call that script via AJAX and parse the JSON to replace the pages array above.
var pages = [];
$.ajax({
url: '/ajax/pages.php',
success: function(json) {
pages = JSON.parse(json);
}
});
You can do this without ever effecting the structure of the URL.
Create a function too control the page flow, with an ajax call
function changePage(page){
$.ajax({
type: 'POST',
url: 'myPaginationFile.php',
data: 'page='+page,
success: function(data){
//work with the returned data.
}
});
}
This function MUST be created as a Global function.
Now we call the function on page load so we always land at the first page initially.
changePage('1');
Then we need to create a Pagination File to handle our requests, and output what we need.
<?php
//include whatever you need here. We'll use MySQL for this example
$page = $_REQUEST['page'];
if($page){
$q = $("SELECT * FROM my_table");
$cur_page = $page; // what page are we on
$per_page = 15; //how many results do we want to show per page?
$results = mysql_query($q) or die("MySQL Error:" .mysql_error()); //query
$num_rows = mysql_num_rows($result); // how many rows are returned
$prev_page = $page-1 // previous page is this page, minus 1 page.
$next_page = $page+1 //next page is this page, plus 1 page.
$page_start = (($per_page * $page)-$per_page); //where does our page index start
if($num_rows<=$per_page){
$num_pages = 1;
//we checked to see if the rows we received were less than 15.
//if true, then we only have 1 page.
}else if(($num_rows % $per_page)==0){
$num_pages = ($num_rows/$per_page);
}else{
$num_pages = ($num_rows/$per_page)+1;
$num_pages = (int)$num_pages;
}
$q. = "order by myColumn ASC LIMIT $page_start, $per_page";
//add our pagination, order by our column, sort it by ascending
$result = mysql_query($q) or die ("MySQL Error: ".mysql_error());
while($row = mysql_fetch_array($result){
echo $row[0].','.$row[1].','.$row[2];
if($prev_page){
echo ' Previous ';
for(i=1;$i<=$num_pages;$i++){
if($1 != $page){
echo "<a href=\"JavaScript:changePage('".$i."');\";> ".$i."</a>";
}else{
echo '<a class="current_page"><b>'.$i.'</a>';
}
}
if($page != $num_pages){
echo "<a class='next_link' href='#' id='next-".$next_page."'> Next </a>';
}
}
}
}
I choose to explicitly define the next and previous functions; so here we go with jQuery!
$(".prev_link").live('click', function(e){
e.preventDefault();//not modifying URL's here.
var page = $(this).attr("id");
var page = page.replace(/prev-/g, '');
changePage(page);
});
$(".next_link").live('click', function(e){
e.preventDefault(); // not modifying URL's here
var page = $(this).attr("id");
var page = page.replace(/next-/g, '');
changePage(page);
});
Then finally, we go back to our changePage function that we built initially and we set a target for our data to go to, preferably a DIV already existing within the DOM.
...
success: function(data){
$("#paginationDiv").html(data);
}
I hope this gives you at least some insight into how I'd perform pagination with ajax and php without modifying the URL bar.
Good luck!