Friday 22 February 2019

Ajax jQuery Load More Data in Laravel



If you have seen any social media sites like Youtube, Twitter or Facebook, in which when page has been load then it has not load all data on web page, when it was load in browser. But in all those sites they have load only last some data on web page, and suppose we want to view more data, then we have to click on load more button. So, this types of techniques we have to implement in Laravel by using ajax jQuery. In this features data will be load dynamically, when user have been click on button, and here it will make pagination without displaying links to user.

Load More or Show More functionality is very simple and user friendly, this is because here all data has not been load at the same time, but it will load only after click on button like pagination, but also it will load more data without refreshing of web page. In this post we will make this type of feature like Load more data from Mysql Database using Ajax in Laravel Framework.

There are two type of load more data feature, one is when user has been click on button then next records has been load on web page, and other is when page has been scroll then next data has been load on web page. But here we will implement load more data on button click event, which we will make in Laravel framework using Ajax jQuery. It will works in a very simple way, and when page has been load then it will load some specific number of data, Suppose we want to view next records, then we have to click on button in which we have define last data id and based on that id it will append next data on web page without refresh of whole page. Because here we have use Ajax with Laravel for implement Load More feature.




Ajax jQuery Load More Data in Laravel


Step 1 - Create Database


Following script will make table in your database.


USE `testing`;

/*Table structure for table `post` */

DROP TABLE IF EXISTS `post`;

CREATE TABLE `post` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `post_title` text,
  `post_description` text,
  `author` varchar(255) DEFAULT NULL,
  `date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=latin1;


Step 2 - Make Database Connection


Once you have create table, and you have insert some records in that table. Now we have move to start creating Load More feature in Laravel. First we want to make database connection. For this we have to go to config/database.php. In this file we have to define database configuration.


<?php

'connections' => [

        ....

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'testing'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

        ..........

    ],

?>


After this we have to open .env file, and this file also we have to define Mysql Database connection configuration.


.......

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=

........


Step 3 - Create Controller (LoadMoreController.php)


After making Mysql Database connection, Now we have to create Controller in Laravel. For this we have to go to command prompt, in which first we have to run "Composer" command, because it has manage Laravel framework dependency. We have to write following command for Create controller in Laravel.


php artisan make:controller LoadMoreController


It will make LoadMoreController.php file under app/Http/Controllers folder. In this controller we have use DB statement for database operation. In this controller we have make following method.

index() - This is root method of this LoadMoreController, which has been load load_more.blade.php file in browser.

load_data() - This method has received ajax request for fetch data from post table and convert into html format and send back to ajax request. In this method if id variable value greater than zero then it will fetch next five data, otherwise it has fetch first five data and convert into HTML and send to Ajax funciton, which has been display on web page.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LoadMoreController extends Controller
{
    function index()
    {
     return view('load_more');
    }

    function load_data(Request $request)
    {
     if($request->ajax())
     {
      if($request->id > 0)
      {
       $data = DB::table('post')
          ->where('id', '<', $request->id)
          ->orderBy('id', 'DESC')
          ->limit(5)
          ->get();
      }
      else
      {
       $data = DB::table('post')
          ->orderBy('id', 'DESC')
          ->limit(5)
          ->get();
      }
      $output = '';
      $last_id = '';
      
      if(!$data->isEmpty())
      {
       foreach($data as $row)
       {
        $output .= '
        <div class="row">
         <div class="col-md-12">
          <h3 class="text-info"><b>'.$row->post_title.'</b></h3>
          <p>'.$row->post_description.'</p>
          <br />
          <div class="col-md-6">
           <p><b>Publish Date - '.$row->date.'</b></p>
          </div>
          <div class="col-md-6" align="right">
           <p><b><i>By - '.$row->author.'</i></b></p>
          </div>
          <br />
          <hr />
         </div>         
        </div>
        ';
        $last_id = $row->id;
       }
       $output .= '
       <div id="load_more">
        <button type="button" name="load_more_button" class="btn btn-success form-control" data-id="'.$last_id.'" id="load_more_button">Load More</button>
       </div>
       ';
      }
      else
      {
       $output .= '
       <div id="load_more">
        <button type="button" name="load_more_button" class="btn btn-info form-control">No Data Found</button>
       </div>
       ';
      }
      echo $output;
     }
    }
}

?>






Step 4 - Create View (load_more.blade.php)


In Laravel, it has use blade engine for process PHP file which has been store under resources/views/load_more.blade.php, it is has display output in browser. Under this file we have use ajax request, which send request to Controller for fetch data and display on web page without refresh of web page. For append data on web page, here we have use jquery append() method.


<!DOCTYPE html>
<html>
 <head>
  <title>Load More Data in Laravel using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Load More Data in Laravel using Ajax</h3><br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Post Data</h3>
    </div>
    <div class="panel-body">
     {{ csrf_field() }}
     <div id="post_data"></div>
    </div>
   </div>
   <br />
   <br />
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 var _token = $('input[name="_token"]').val();

 load_data('', _token);

 function load_data(id="", _token)
 {
  $.ajax({
   url:"{{ route('loadmore.load_data') }}",
   method:"POST",
   data:{id:id, _token:_token},
   success:function(data)
   {
    $('#load_more_button').remove();
    $('#post_data').append(data);
   }
  })
 }

 $(document).on('click', '#load_more_button', function(){
  var id = $(this).data('id');
  $('#load_more_button').html('<b>Loading...</b>');
  load_data(id, _token);
 });

});
</script>


Step 5 - Set Route


After this we have to set route of Controller method in Laravel framework. For this we have to open routes/web.php file.


Route::get('/loadmore', 'LoadMoreController@index');
Route::post('/loadmore/load_data', 'LoadMoreController@load_data')->name('loadmore.load_data');


Step 6 - Run Laravel Application


For run Laravel application, we have to go command prompt and write following commend, it will run Laravel application and display base url of Laravel application.


php artisan serve


It will return follwing url and for run this code you have to write following url.


http //127.0.0.1


This is complete step by step process with source code for make Load More data feature in Laravel by using Ajax jQuery with Mysql Database.

4 comments: