Load more posts without page reload using Ajax and jQuery [Like Twitter and Facebook]

  1. Previous
  2. Next
  3. Recent

    1. Signs 'He' May be Cheating on You
    2. 7 Vows of Hindu Marriage - Know What 'Saat Vachans' Mean
    3. RuPay vs Visa vs Mastercard vs American Express- A Comparison
    4. What is RuPay? Everything You Need to Know About India's Domestic Payment System!
    5. Top 10 Online Portals to Find a High Paying Job in India
    6. Top Indians who Revolutionized the IT Sector in India
    7. 8 Initiatives by Narendra Modi that Could Change the Future of the Nation
    8. 8 Work-from-home Jobs for Housewives, Students, and Part timers
    9. Complete Company Registration Process in India - Explained
    10. Change Name in India in 5 Steps - Filing Affidavit, Newspaper Ad & Gazette Notification

In Twitter, you must have seen a ‘More Tweets’ tab at the bottom to load older tweets. The same thing is present in Facebook to load older posts. In most Web 2.0 sites like Digg and StumbleUpon, the entire system is such that the posts/tweets/updates are loaded with no page refresh. This is a great feature that greatly enhances the user-experience for a website.

This is done using Ajax and jQuery – an awesome technology for exchanging data to-and-fro to a web server without reloading the entire webpage.

If you’re planning to build the same in your upcoming web project then follow our tutorial where we tell everything about building such interface to load more posts/entries from the database. Here is a demo of what we’ll be building.

[To use the same code given in the tutorial, make a database with name ‘test’, and a table called ‘quiz_techno’ inside it. In ‘quiz_techno’, make 2 fields: ‘qid’ and ‘question’. qid is integer id of text questions. Fill 10-15 entries. Understand the tutorial and then execute the downloaded files in your local webserver like XAMPP.]

First create a folder ‘Tutorial-1’ in your local XAMPP installation. All files would go inside this folder.

The Database Connection

As all posts/entries are all loaded from a central database. So, to retrieve them from our database, we must create a connection to it. Here is the demo code for making connection to a MySQL database [Note: Replace username and password with yours].

Create a file ‘dbcon.php’ and copy the following code inside it,


<?php
 $con=mysql_connect("localhost","root","") or die("Database connection failed");
 if($con)
 {
 mysql_selectdb("test",$con);
 }
?>

Place the file inside ‘Tutorial-1’ folder.

The PHP Code

The next step is to design the ‘index.php’ page. Here is the code,


<?php
include_once 'dbcon.php';
?>

<center>
<div id='defaultquestions'>
<?php
$query=mysql_query("SELECT question FROM quiz_techno ORDER BY qid ASC LIMIT 3");
while($geteach=mysql_fetch_array($query))
{
echo "<p class='posts'>".$geteach[0]."</p>";
}
?>
</div>
<div id='morequestions'></div>
<p id='more'>show more</p>
</center>

Here we’ll be doing a few things:

  1. First we include the file that makes connection to the database. So ‘dbcon.php’ file is loaded first.
  2. Next we make query to database and retrieve the last 3 posts/entries. Its displayed inside <p class=’posts’>—Last 3 posts—</p>
  3. [Important] This <div id=’morequestions’></div> will show the more posts/entries retrieved using Ajax.
  4. When the ‘show more’ tab is clicked, request to server is made and 3 more posts/entries are loaded inside the <div id=’morequestions’></div>. Posts continue to load as user keeps pressing the ‘show more’ tab.

The CSS Code

The CSS portion stylizes the webpage HTML components. [Tutorial would work fine even after skipping this CSS code. The code is simple but you can skip this part if find difficult to understand.]

<style>

div#defaultquestions, div#morequestions
{
 width:550px;
 font-family:Tahoma,Arial;
 font-size:12px;
 text-align:left;
}

p.posts
{
 margin:3px;
 padding:10px;
 background:#F3FAFB;
 border-top:1px solid #EBF2F3;
}

p.posts img
{
 margin:right:5px;
}

p#more
{
 width:534px;
 height:15px;
 padding:5px;
 background:#C3D3F1;
 border:1px solid #AAC1EB;
 color:white;
 text-align:center;
 font-family:Tahoma,Arial;
 font-size:12px;
 font-weight:bold;
 margin-top:10px;
 -moz-border-radius:3px;
 -webkit-border-radius:3px;
 border-radius:3px;
 cursor:pointer;
}

p#more:hover
{
 background:#AAC1EB;
}

</style>

The jQuery Code

This is the most important part wherein we receive the ‘click’ event generated when ‘more posts’ tab is clicked. This sends an Ajax GET Request to the ‘load.php’ file at the server. The ‘load.php’ file collects entries from the database and show them inside the <div id=’morequestions’></div> without loading the page.

Here we’re using jQuery to make Ajax get request to server. [The same thing can also be done using JavaScript only. jQuery simplifies the code by a big margin.]

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<script language='Javascript'>

var ptr=1;
$('p#more').click(function()
{
param="from="+ptr;
divptr="div"+ptr++;
$('div#morequestions').append("<div class='divptr' id="+divptr+"></div>");

$('p#more').html("<img src='img/l.gif'>");
$.get('load.php',param,function(data){
$('div#'+divptr).html(data);
$('div.divptr').css({'borderLeft':'none'});
$('div#'+divptr).css({'borderLeft':'1px solid orange'});
$('p#more').html("show more");});
});

</script>

Some things to note in the jQuery code are,

  1. First we load ‘jQuery.js’ from Google’s CDN. This is important otherwise tutorial won’t work.
  2. [Important] The JavaScript variable ‘ptr’ is incremented by 1 everytime user hits the ‘more posts’ button. Initially, its 1 when we’re showing first 3 posts. When clicked for the first time ‘ptr’ increments to 2, and the next 3 posts (from 3 to 6) are retrieved from server and displayed. Similarly, when ptr is 3, results from 9 to 12 is retrieved and shown. The process continues like this till user keeps on hitting the ‘more posts’ tab.
  3. [Important] On every click, we’re dynamically creating a new div inside the <div id=’morequestions’></div>, as seen in the step 9-10. Carefully observe the id of every newly created div which is like divptr=”div”+ptr++; where the variable ‘ptr’ changes with every ‘more posts’ tab hits. So every new div would be like div1, div2, div3… that displays 3 entries one after each other.Here is how the code would appear after a user presses ‘more posts’ 3 times,<div id=’defaultquestions’> 3 posts </div>

    <div id=’morequestions’>
    <div id=’div1′> 3 more posts [4-6] </div>
    <div id=’div2′> 3 more posts [7-9] </div>
    <div id=’div3′> 3 more posts [10-12] </div>
    .
    .
    .
    <div id=’divX’> 3 more posts [last 3] </div>

    </div>

The load.php file

The final piece of code is the ‘load.php’. This is the php file that retrieves posts/entries from server database and display,

<?php
include_once 'dbcon.php';
?>

<?php $from=$_GET['from']*3; ?>

<?php
$query=mysql_query("SELECT question FROM quiz_techno ORDER BY qid ASC LIMIT $from,3");
while($geteach=mysql_fetch_array($query))
{
echo "<p class='posts'>".$geteach[0]."</p>";
}
sleep(1);
?>

The above code is self-explanatory. Here we’re including the ‘dbcon.php’ file to make database connection. Next we get the parameter from the Ajax request, and increase it by multiple of 3 (like 3, 6, 9, 12, 15 and so on). And finally we load 3 new entries from the database and send back to the browser to display.

sleep(1) is for reducing load on server and to allow animation to appear while Ajax request is processed by the server.

Download Tutorial

Please download the tutorial to better understand the code. You can improve it and use in your web projects.

[Note: All files should be saved inside one folder. Here we have named it as ‘Tutorial-1’, you can name anything of your liking.]

I have tried my best to make the code clear and easy to understand. If there is any improvement possible or any query, please mention in comments.

blog comments powered by Disqus