How to Ajax Pagination in Laravel 5

Ajax makes your application more flexible, you don’t need to reload or refresh the whole body for small changes, you can made changes in any part without loading page.

Generate Pagination

Route

Route::get('/view-device','DeviceController@index');

View Call

public function index()
{
    return view('device.view_device');
}

Html Code

<meta name="csrf-token" content="{{ csrf_token() }}">
<table class="table table-bordered" id="items">
<thead>
  <tr>
    <th style="text-align:center;">Item Name</th>
    <th style="text-align:center;">Sub Item Product</th>
    <th style="text-align:center;">Vat%</th>
    <th style="text-align:center;">Rate</th>
    <th style="text-align:center;">Created Date</th>  
    <th style="text-align:center;">Action</th>
  </tr>
  </thead>
  <tbody id="renderstring">
  </tbody>
</table>
<div class="pagi"></div>

Jquery Call

function renderstring()
{
  $.ajax({
      url: "{{url('getdevicelist')}}",
      data:"",
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      type:"POST",
      dataType: "json",
      success: function(json) {
          $('#renderstring').html(json.success);
          $('.pagi').html(json.pagi);
      },
  });
}
renderstring();

Call to routes

Route::post('getdevicelist','DeviceController@getdevicelist');

Route to Controller

public function getdevicelist(Request $request)
{
	$str = '';
	$data = Device::orderBy('id', 'desc')->paginate(10);	
	if(!empty($data))
	{
		foreach ($data as  $device) {
			$childprint = '';
			$str.='<tr><td style="text-transform:capitalize;">'.$device->item_name.'</td>';
			$str.='<td>'.$childprint.'%</td>';
			$str.='<td >'.$device->vat.'%</td>
			<td>'.number_format((int)$device->rate, 2).'</td>
			<td>'.$device->created_at.'</td>
			<td><button class="btn btn-danger" id='.$device->id.'>Delete</button></td></tr>';
		}
		$json['success'] = $str;
		$json['pagi'] = ''.$data->links().'';	
	}
	else
	{
		$json['success'] = '<tr><td colspan="100%">No Record Found!!</td></tr>';
	}
	echo json_encode($json);
}

Now finally call pagination.

$('.pagi').delegate('.pagination a','click',function(event){
    event.preventDefault();
    var pagiurl = $(this).attr('href');
    $.ajax({
            url: pagiurl,
            data:"",
            headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type:"POST",
            dataType: "json",
            success: function(json) {
                $('#renderstring').html(json.success);
                $('.pagi').html(json.pagi);
            }
    });
});

Leave a Reply

Your email address will not be published. Required fields are marked *