Load more function with jQuery, MySQL and PHP based on ajax

Hi friends, in this tutorial, I will show Load more button for loading new content.
When  one clicks the load button, the next list of data from database is being fetched and append it to the last of existing data in your view page.



Index.php:-
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
 <p id="head">Load More Function From Database Using Ajax, jQuery, PHP and MySQL</p>
 <div id="content">
  <div id="result">
  <?php
  mysql_connect('localhost','root','');
  mysql_select_db('dbname');
  
  $select = mysql_query("select * from tablename limit 0,6");
  while($row = mysql_fetch_array($select))
  {
   echo "<p class='result'>".$row['colname1']."<br>".$row['colname2']."</p>";
  }
  ?>
  </div>
  <input type="hidden" id="result_no" value="6">
  <input type="button" id="load" value="Load More">
 </div>
</body>
</html>

Style.css:-
 body
{
 background-color:#E6E6E6;
 font-family:helvetica;
}
#head
{
 margin-top:150px;
 width:600px;
 font-size:27px;
 color:#2E2EFE;
}
.result
{
 text-align:left;
 background-color:grey;
 width:400px;
 padding:10px;
 box-sizing:border-box;
 color:#F2F2F2;
 border-radius:3px;
 border:1px solid #424242;
 font-style:italic;
}
#load
{
 width:400px;
 height:40px;
 color:brown;
 background-color:brown;
 border-radius:3px;
 color:white;
 border:none;
 font-size:17px;
}

Script.js:-
$(document).ready(function(){
 $("#load").click(function(){
  loadmore();
 });
});

function loadmore()
{
 var val = document.getElementById("result_no").value;
 $.ajax({
 type: 'post',
 url: 'ajax.php',
 data: {
  getresult:val
 },
 success: function (response) {
  var content = document.getElementById("result");
  content.innerHTML = content.innerHTML+response;
  document.getElementById("result_no").value = Number(val)+6;
 }
 });
}

Ajax.php:-

<?php
 mysql_connect('localhost','root','');
 mysql_select_db('dbname');

 $no = $_POST['getresult'];
 $select = mysql_query("select * from tablename limit $no,2");
 while($row = mysql_fetch_array($select))
 {
  echo "<p class='result'>".$row['colname1']."<br>".$row['colname2']."</p>";
 }
?>

Comments