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:

  1. pagination requires two main variables. $page and $itemsPerPage.
  2. Using above variable, you will create a query limit
  3. 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);
   });
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!