phpajaxlaraveldatatablesyajra-datatable

Laravel datatable ajax post request


I am developing a Laravel management application with Yajra datatables.

So I have various tables, and in particular in the user table I need to change the user's status (active / inactive) via ajax request by simply clicking a button or ticking a checkbox. This is my first time using ajax and datatables, and I have no idea how to achieve this ... is it possible or are there better / quicker ways to do this?

I accept any advice or suggestion

My code:

<?php

namespace Modules\User\Http\Controllers;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\User;
use DataTables;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request)
    {
        $user = User::select('id', 'name', 'email', 'attivo' , 'email_verified_at', 'created_at')->get();
        if($request->ajax()){
            return Datatables::of($user)
                    ->addIndexColumn()
                    ->addColumn('stato', function($row){
                        ($row['attivo'] == 1 ) ? $btn1 = '<div class="btn-group" role="group" aria-label="Basic example"><a href="#" id="btn-post" dusk="postButton" class="btn btn-primary" role="button" data-toggle="modal" data-target="#addPost"  style="color:white; font-size:small;">
                        <span class="ion-plus-circled"> Disattiva</span>
                      </a>'
                        : $btn1 = '<div class="btn-group" role="group" aria-label="Basic example"><button id="btnAttiva" class="btn btn-primary btn-rounded" style="color:white; font-size:small;">Attiva</button>';
                        
                        return $btn1;
                    })
                    ->addColumn('action', function($row){
                           $btn = '<div class="btn-group" role="group" aria-label="Basic example"><a href="/user/detail/'.$row['id'].'" class="btn btn-primary btn-rounded" style="color:white; font-size:small;">View</a></div>';
                           $btn = $btn.'<a href="/user/edit/'.$row['id'].'" class="edit btn btn-success btn-rounded" style="color:white; font-size:small;">Edit</a>';
                           $btn = $btn.'<form action="/user/delete" method="POST"><input type="hidden" name="_token" value="{{ @csrf() }}"><input type="hidden" name="_method" value="{{ @method(\'delete\') }}">
                           <input type="hidden" class="form-control" name="idu" value="'.$row['id'].'"><input type="submit" class="edit btn btn-danger btn-rounded" style="color:white; font-size:small;" value="Delete" /></form></div>';
         
                            return $btn;
                    })
                    ->rawColumns(['action', 'stato'])
                    ->make(true);

        }
        return view('user::index');
    }

    public function setState(Request $request){
        // here i need to modify the user state
    }
}
@extends('layouts.master')
@section('title', 'Lista Utenti')
@section('content')

@if (\Session::has('error'))
<div class="alert alert-danger">
    <ul>
        <li>{!! \Session::get('error') !!}</li>
    </ul>
</div>
@endif
@if (\Session::has('success'))
<div class="alert alert-success">
    <ul>
        <li>{!! \Session::get('success') !!}</li>
    </ul>
</div>
@endif
<div class="col-lg-12 grid-margin stretch-card">
    <div class="card">
        <div class="card-body">
            <h4 class="card-title">Utenti</h4>
            <p class="card-description">
                Lista degli utenti registrati
            </p>
            <div class="table-responsive">
                <table class="table table-bordered" id="dtUserList">
                    <thead>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Email Verificata</th>
                        <th>Stato</th>
                        <th>Created</th>
                        <th>Action</th>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</div>
<div>
    <a href="{{ url('/user/create') }}" class="btn btn-primary btn-rounded"
        style="color:white; font-size:small;">Aggiungi utente</a>
</div>
@endsection

@section('script')

<script>
    $(function() {
       var table =  $('#dtUserList').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{{ url('user') }}',
            columns: [
                { data: 'id', name: 'id', visible: false },
                { data: 'name', name: 'name' },
                { data: 'email', name: 'email' },
                { data: 'email_verified_at', name: 'email_verified_at'},
                { data: 'stato', name: 'stato', orderable: false, searchable: false},
                { data: 'created_at', name: 'created_at' },
                { data: 'action', name: 'action', orderable: false, searchable: false },
            ],
            order: [[0, 'asc']]
        });
    });
</script>
@endsection

EDITED CODE WITH AJAX CALL:

@extends('layouts.master')
@section('title', 'Lista Utenti')
@section('content')

@if (\Session::has('error'))
<div class="alert alert-danger">
    <ul>
        <li>{!! \Session::get('error') !!}</li>
    </ul>
</div>
@endif
@if (\Session::has('success'))
<div class="alert alert-success">
    <ul>
        <li>{!! \Session::get('success') !!}</li>
    </ul>
</div>
@endif
<div class="col-lg-12 grid-margin stretch-card">
    <div class="card">
        <div class="card-body">
            <h4 class="card-title">Utenti</h4>
            <p class="card-description">
                Lista degli utenti registrati
            </p>
            <div class="table-responsive">
                <table class="table table-bordered" id="dtUserList">
                    <thead>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Email Verificata</th>
                        <th>Stato</th>
                        <th>Created</th>
                        <th>Action</th>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</div>
<div>
    <a href="{{ url('/user/create') }}" class="btn btn-primary btn-rounded"
        style="color:white; font-size:small;">Aggiungi utente</a>
</div>
@endsection

@section('script')

<script type="text/javascript">
    $(function() {
       var table =  $('#dtUserList').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{{ url('user') }}',
            columns: [
                { data: 'id', name: 'id', visible: false },
                { data: 'name', name: 'name' },
                { data: 'email', name: 'email' },
                { data: 'email_verified_at', name: 'email_verified_at'},
                { data: 'stato', name: 'stato', orderable: false, searchable: false},
                { data: 'created_at', name: 'created_at' },
                { data: 'action', name: 'action', orderable: false, searchable: false },
            ],
            order: [[0, 'asc']]
        });
    });

    $.fn.myFunction = function(form){
        //put the form elements in an array
        id = $(form).serializeArray();
        //Get the value of the first index(the id)
        iduser = id[0]['value'];
        idstato = id[1]['value'];
            $.ajax({
                // Post method
                type: 'POST',
                // Url to the route
                url: "{{ url('/user/deactivate') }}",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                // Data to submit to the function
                data: {
                    //CRSF token for laravel form validations
                    _token: $('meta[name="csrf-token"]').attr('content'),
                    idu: iduser,
                    ids: idstato
                },
    success: function(response){
        //if request is made successfully then the response represent the data
        $( "#result" ).empty().append( response );
    }
  });
}
</script>
@endsection
<?php

namespace Modules\User\Http\Controllers;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\User;
use DataTables;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request)
    {
        $user = User::select('id', 'name', 'email', 'attivo' , 'email_verified_at', 'created_at')->get();
        if($request->ajax()){
            return Datatables::of($user)
                    ->addIndexColumn()
                    ->addColumn('stato', function($row){
                        ($row['attivo'] == 1 ) ? $btn1 = '<form><input type="hidden" name="user" value="'.$row['id'].'"><div class="form-group"><select onchange="$.fn.myFunction(this.form)" name="stato"><option value="0">Disattivo</option><option value="1" selected>Attivo</option></select></div></form>'
                        : $btn1 = '<form><div class="form-group"><input type="hidden" name="user" value="'.$row['id'].'"><select name="stato" onchange="$.fn.myFunction(this.form)"><option value="0" selected>Disattivo</option><option value="1">Attivo</option></select></div></form>';
                        
                        return $btn1;
                    })
                    ->addColumn('action', function($row){
                           $btn = '<div class="btn-group" role="group" aria-label="Basic example"><a href="/user/detail/'.$row['id'].'" class="btn btn-primary btn-rounded" style="color:white; font-size:small;">View</a></div>';
                           $btn = $btn.'<a href="/user/edit/'.$row['id'].'" class="edit btn btn-success btn-rounded" style="color:white; font-size:small;">Edit</a>';
                           $btn = $btn.'<form action="/user/delete" method="POST"><input type="hidden" name="_token" value="{{ @csrf() }}"><input type="hidden" name="_method" value="{{ @method(\'delete\') }}">
                           <input type="hidden" class="form-control" name="idu" value="'.$row['id'].'"><input type="submit" class="edit btn btn-danger btn-rounded" style="color:white; font-size:small;" value="Delete" /></form></div>';
         
                            return $btn;
                    })
                    ->rawColumns(['action', 'stato'])
                    ->make(true);

        }
        return view('user::index');
    }

    public function disattiva($idu, $ids){
        dd($idu+":"+$ids);
    }
}
//rotte USER module with CRUD route
Route::middleware(['auth'])->prefix('user')->group(function() {
    Route::get('/', 'UserController@index'); //dashboard -> lista utenti
    Route::post('/deactivate', 'UserController@disattiva');
    Route::get('/detail/{idu}', 'UserController@show'); // dettaglio specifico utente
    Route::get('/edit/{idu}', 'UserController@showEditForm'); // form edit utente con dato idu
    Route::patch('/edit', 'UserController@edit'); // scrivere le modifiche sul DB
    Route::delete('/delete', 'UserController@destroy'); // eliminare utente dal DB
    Route::get('/create', 'UserController@showCreateForm'); // form creazione nuovo utente
    Route::post('/create', 'UserController@create'); // creare l'utente sul DB
    Route::get('/profile', 'UserController@showProfile'); // mostra il profilo dell'utente loggato
});


Solution

  • Create a form inside your table and create a custom function in the select (I assume you want to change it using a select) <select onchange="$.fn.myFunction(this.form)">

    After that you want to create a ajax request like this:

    $.fn.myFunction = function(form){
            //put the form elements in an array
            id = $(form).serializeArray();
            //Get the value of the first index(the id)
            id = id[0]["value"];
                $.ajax({
                    // Post method
                    type: 'POST',
                    // Url to the route
                    url: "/ajax/myfunction",
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    // Data to submit to the function
                    data: {
                        //CRSF token for laravel form validations
                        _token: $('meta[name="csrf-token"]').attr('content'),
                        id: id
                    },
        success: function(response){
            //if request is made successfully then the response represent the data
            $( "#result" ).empty().append( response );
        }
      });
    }