Laravel Datatable - Ajax | Shahul Hameed

Overview Image:

 


Database Structure


Step 1: Import library files - Datatable

    CSS Library CDN :

    <link rel="stylesheet" type="text/css"
    href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.css">

  JS Library CDN
    
    <script type="text/javascript" charset="utf8"
    src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.js"></script>

Step 2: Blade code - main.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TO-DO List</title>
    <!-- Bootstrap CDN link -->
    <link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
    integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
    crossorigin="anonymous">
    <!-- Datatable CDN link -->
    <link rel="stylesheet" type="text/css"
    href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.css">
</head>
<body>
<div class="page-content pt-5 content-boxed">
<div class="content-wrapper">
  <div class="content">
    <div class="card Neu-card">
      <div class="card-body">
        <div class="card-header">  
          <table class="table " id="logTable">
            <thead>
                 <tr class="TableHead">
                    <th class="text-center threat-text-affect">No:</th>
                    <th class="text-center threat-text-affect">Product</th>
                    <th class="text-center threat-text-affect">Category</th>
                    <th class="text-center threat-text-affect">Rate</th>
                    <th class="text-center threat-text-affect">Updated_At</th>
                    <th class="text-center threat-text-affect">Action</th>
                </tr>
              </thead>
                   
              <tbody>
                 <!-- data comes from ajax -->
              </tbody>    

         </table>
          </div>
        </div>
      </div>
  </div>
</div>
</div>


<!-- Start Edit To-Do Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">

      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Update Data</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body">
     
        <form name ="" method="post" id="update-form">
            @csrf
            <!-- {{ method_field('PUT') }} -->
            <input type="hidden" class="form-control" id="id" name="id">
            <div class="row mb-3">
                <label class="col-sm-2 col-form-label">Name</label>
                <div class="col-sm-10">
                <input type="text" class="form-control" id="name" name="name">
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-2 col-form-label">First Name</label>
                <div class="col-sm-10">
                <input type="text" class="form-control" id="f_name" name="f_name">
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-2 col-form-label">Last Name</label>
                <div class="col-sm-10">
                <input type="text" class="form-control" id="l_name" name="l_name">
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-2 col-form-label">Email</label>
                <div class="col-sm-10">
                <input type="text" class="form-control" id="email" name="email">
                </div>
            </div>

            <div class="modal-body">
                <h6 class="font-weight-semibold">Impact</h6>
                <p id="impact_VM"></p>
            </div>

            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
        </form>
      </div>
     
    </div>
  </div>
</div>
<!-- End Edit To-Do Modal -->

<!-- Jquery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>

<!-- Datatable CDN -->
<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.js"></script>

<!-- Bootstrap Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
 crossorigin="anonymous"></script>

<script src="{{ asset('js/script.js') }} "></script>
</body>
</html>

  
Step 3: JsScript code - public/script.js

 
// Start Get datatable from Record
var i = 1;
var vulnerabilityData = $("#logTable").DataTable({
        "filter":true,
        "processing": true,
        "serverSide": false,
        "retrieve": true,
        "ajax": {
            "url" : '/log-user',
            "dataType": "json",
        },
        "columns": [
            {
                "data": null,"sortable": false,
                "render": function(data, type, row, meta) {
                    return meta.row + meta.settings._iDisplayStart + 1;
                }
            },
            {
            data: 'name', //from db column
            },
            {
            data: 'description', //from db column
            },
            {
            data: 'category', //from db column
            },
            {data: 'created_at'}, //from db column
            {
            data: null,
            render:function(data, type, row)
            {
               
            var id = data.id;  //id from db
            return '<button id="actionButton" type="button"
            class="btn btn-secondary dropdown-toggle" data-toggle="dropdown"
            aria-haspopup="true" aria-expanded="false">Action</button>
            <div class="dropdown-menu" aria-labelledby="actionButton">  
            <a class="dropdown-item" onclick="editRecord(\''+id+'\')"
            data-toggle="modal" href="#"><i class="icon-checkmark3 text-success"></i>
            Edit Record</a><a class="dropdown-item" onclick="deleteRecord(\''+id+'\')"
           data-toggle="modal" href="#"><i class="icon-checkmark3 text-success">
            </i>Delete</a></div>';
            },
            "targets": -1
            },

        ]
       
    });
// End Get datatable from Record

//Delete record
function deleteRecord(id)
{
    var id = id;
    $.ajax({
    url: '/deleteData/'+ id,
    type: 'get',
    dataType:"JSON",
    data:{
        id:id
    },
    success:function(data)
    {
        alert('deleted');
        location.reload();
    }
    });
}
//End delete record

//Edit record
function editRecord(id)
{

    var id = id;
    //console.log(id);
    $.ajax({
    url: '/viewData/'+ id,
    type: 'get',
    dataType:"JSON",
    data:{
        id:id
    },
    success:function(data)
    {
        $('#id').val(data[0].data[0].id);
        $('#name').val(data[0].data[0].name);
        $('#f_name').val(data[0].data[0].description);
        $('#l_name').val(data[0].data[0].category);
        $('#email').val(data[0].data[0].created_at);
        $('#impact_VM').html(data[0].data[0].created_at);  //paragraph tag
        $('#editModal').modal('show');
       
    }
    });
}
//End edit record

$('#update-form').on('submit',function(event){
    event.preventDefault();
   
    var id = $('#id').val();
    //console.log(id);

    $.ajax({
      url: '/update/'+ id,
      type:"post",
      data:$('#update-form').serialize(),

      //Display Response Success Message
      success: function(data){
          //console.log('end');
          $('#editModal').modal('hide');
          $('#logTable').DataTable().ajax.reload();
          alert('updated');
       
      },
      error:function(error)
      {
        console.log(error);
      }
    });


});
  
Step 4: Controller - TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class TestController extends Controller
{

//Start datatable view function
public function dataTable()
    {
   
        $data = DB::table('tasks')->get();   //Your table name here
           
        return response()->json(['data'=> $data]);
    }
//End datatable view function

//Start delete function
public function deletetLog($id)
{
   
    $delete_id = $id;
    //Note table
    $delete_query = DB::table('tasks')->where('id', $delete_id)->delete();

    if($delete_query){
         return response()->json([
         'message' => 'Record has been deleted successfully!',
         'status'  => true
        ]);
    }

    else{
        return response()->json([
            'message' => 'Internal Error',
            'status'  => false
        ]);
    }
}
//End delete function

//Start edit function
public function editRecordData($id)
{
 
    $data = DB::table('tasks')   //Note table
    ->select('*')
    ->where('id',$id)
    ->get();

    //pass to js ajax data
    $final_data[] = array(
        'data'=>$data
    );

    return $final_data;
   
}
//End edit function

//Start update function
public function updateData(Request $req, $id)
{  

    $data = DB::table('tasks')
    ->where('id',$id)
    ->update([
        'name' => $req->name,
        'description' => $req->f_name,
        'category' => $req->l_name,
        'created_at' => $req->email,
    ]);

    if ($data) {
        return response()->json([
            'status' => true,
            'message' => 'New Alerts Added Successfully ',
        ]);
    }
    else {
        return response()->json([
            'status' => false,
            'message' => 'Internal server error please try again.',
        ]);
    }
}
//End update function
   
}

Step 5: Route - web.php

Route::view('/test', 'main'); //blade view
Route::get('/log-user', 'TestController@dataTable');
Route::get('deleteData/{id}','TestController@deletetLog');
Route::get('viewData/{id}','TestController@editRecordData');
Route::post('update/{id}', 'TestController@updateData');



  

Comments

Popular posts from this blog

Using Burp Suite - Brute Force payloads using XSS Validator(Extension) | Shahul Hameed

Janus Vulnerability Exploitation

SQL Basics | Shahul Hameed