load more dengan ajax jquery php mysqli

Posting Komentar
Tutorial kali ini lacodeid akan membahas salah satu fitur yang  sering digunakan dalam setiap pembuatan website terutama bagian menampilkan data dan membatasi tampilan data dengan fitur yang satu ini masalah bisa diatasi dengan baik tanpa mengurangi kualitas website itu sendiri, salah satunya fitur Load more dengan ajax, pasti anda sudah tidak sabar ingin melihat kelebihan fitur yang satu ini tenang anda bisa langsung ikuti langkah dibawah ini :

pertama yang harus anda download disini JQUERY  nya karena tanpa Jquery Load more ini nantinya tidak akan berjalan sesuai dengan harapan anda jadi silakan download Jquerynya dulu.

lalu buat tabel penampung datanya seperti dibawah ini :

CREATE TABLE IF NOT EXISTS `paginate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) NOT NULL,
  `message` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ;
lalu anda buat file config.php dalam folder localhost latihan anda terus copas koding dibawah ini, file config.php ini untuk menghubungkan databasenya
<?php
$db_username = 'root';
$db_password = 'password';
$db_name = 'name database';
$db_host = 'localhost';
$item_per_page = 5;//limit data yang akan ditampilkan

$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
lalu buat file fetch_pages.php satu folder dengan file config.php, file ini nantinya yang akan menampilkan data dalam database, untuk kodingnya silakan anda copas dibawah ini :
<?php
 include("config.php"); //include config file
 //sanitize post value
 $page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);

 //throw HTTP error if page number is not valid
 if(!is_numeric($page_number)){

  header('HTTP/1.1 500 Invalid page number!');
  exit();

 }

 //get current starting point of records
 $position = (($page_number-1) * $item_per_page);
 //fetch records using page position and item per page. 
 $results = $mysqli->prepare("SELECT id, name, message FROM paginate ORDER BY id DESC LIMIT ?, ?");
 //bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
 //for more info https://www.sanwebe.com/2013/03/basic-php-mysqli-usage
 $results->bind_param("dd", $position, $item_per_page); 
 $results->execute(); //Execute prepared Query
 $results->bind_result($id, $name, $message); //bind variables to prepared statement

 //output results from database

 while($results->fetch()){ //fetch values
  echo '<p>'.$id.') <strong>'.$name.'</strong> : '.$message.'</p>'; 
 }
selanjutnya anda buat file index.php satu folder dengan file config.php tadi, untuk kodingnya silakan anda copas dibawah ini :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Load more</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css">
<link href="https://fonts.googleapis.com/css?family=Rubik" rel="stylesheet">
<style type="text/css">
 .wrapper {
  width: auto;
  margin: 0 auto;
  font-family: Georgia, "Times New Roman", Times, serif;
 }
 .wrapper > ul#results li{ 
  margin: 1px 0; 
  background: #f9f9f9; 
  padding: 20px; 
  list-style: none;
 }
 p {
     margin: 0 0 10px;
     background-color: #f7f7f7;
     padding: 10px;
     border-radius: 3px;
 }
 button {
  padding: 8px 20px;
  background: #fbfbfb;
  border: 1px solid #f7f7f7;
  border-radius: 4px;
  height: 37px;
  min-width: 130px;
 }
 button:hover, 
 button:active, 
 button:focus{
  background: #f3f3f3;
  outline: none;
 }
</style>
</head>
<body>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">LOAD MORE</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>
      </ul>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

<div class="container">
 <div class="row">
  <div class="col-lg-12">
   <div class="wrapper">

       <div id="results"></div><!-- show data disini -->

       <div align="center">
           <button id="load_more_button"><img src="ajax-loader.gif"  class="animation_image" style="float:left;"> Load More</button> <!-- load button -->
       </div>
       <br>
   </div>
  </div>
 </div>
</div>

<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">

 var track_page = 1; //track user click as page number, righ now page number 1

 load_contents(track_page); //load content

 $("#load_more_button").click(function (e) { //user clicks on button
  track_page++; //page number increment everytime user clicks load button
  load_contents(track_page); //load content
 });

 //Ajax load function
 function load_contents(track_page){

  $('.animation_image').show(); //show loading image

  $.post( 'fetch_pages.php', {'page': track_page}, function(data){

   if(data.trim().length == 0){
    //display text and disable load button if nothing to load
    $("#load_more_button").text("You have reached end of the record!").prop("disabled", true);
   }

   $("#results").append(data); //append data into #results element

   //scroll page to button element
   $("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 1000);

   //hide loading image
   $('.animation_image').hide(); //hide loading image once data is received
  });
 }

</script>

</body>
</html>
potongan script dibawah ini nantinya yang akan berfungsi untuk menampilkan data setelah tombol load more di klik cantik
var track_page = 1; //track user click as page number, righ now page number 1
load_contents(track_page); //load content
$("#load_more_button").click(function (e) { //user clicks on button
 track_page++; //page number increment everytime user clicks load button
 load_contents(track_page); //load content
});
//Ajax load function
function load_contents(track_page){
 $('.animation_image').show(); //show loading image
 $.post( 'fetch_pages.php', {'page': track_page}, function(data){
  if(data.trim().length == 0){
   //display text and disable load button if nothing to load
   $("#load_more_button").text("You have reached end of the record!").prop("disabled", true);
  }
  $("#results").append(data); //append data into #results element
  //scroll page to button element
  $("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 1000);
  //hide loading image
  $('.animation_image').hide(); //hide loading image once data is received
 });
}
dari potongan beberapa kode diatas saya rasa sudah cukup menambah sedikit ilmu anda cara membuat load more dengan ajax tidak sulit kalo anda mau belajar dan belajar untuk lebih lanjutnya silakan anda kembangan sendiri

Related Posts

Posting Komentar