March 22, 2012
How to Implement Pages Feature like YouTube / Other sites?
Question by Delos Chang
I’m still new to Javascript and would like to create a ‘pages’ feature for comments and replies.
YouTube videos have a very nice pagination feature that pages the comments well.
How do I go about doing this? My current setup is with PHP, Javascript, and MySQL.
Answer by Starx
Youtube sends an ajax request back to the server and fetches the results which is updated to the page currently viewed. Other sites also use similar technique.
Basic thing you need to know are:
- pagination requires two main variables.
$page
and$itemsPerPage
. - Using above variable, you will create a query limit
- You will use this limit in your query to fetch the result of the next page.
Example:
$page = (int)$_POST['page'];
$itemsPerPage = 10; //Generally this might be static
$limit = (($page-1)*$itemsPerPage).",".$itemsPerPage;
// For the Page 1, this give 0,10
$query = "SELECT ... LIMIT $limit";
//Translates to LIMIT 0,10 so takes out the first 10 records or in other words first page
//get the records, creat the markup and echo them
Now, as part of Javascript, here is an example of jQuery Post Request
$("#yourpageonelink").click(function() {
$.post("yourpage.php", {
page: 1 // I am using static value for demo, but you should get this dynamically
}, function(data) {
//Now data will get the content returned from the php file
// So update the div
$("#mainContainer").html(data);
});
});