Laravel 数据表 ajax post 请求

Laravel datatable ajax post request

我正在使用 Yajra 数据 table 开发 Laravel 管理应用程序。

所以我有各种 tables,特别是在用户 table 中,我需要通过 ajax 请求更改用户的状态(活动/非活动),只需单击按钮或勾选复选框。 这是我第一次使用 ajax 和 datatables,我不知道如何实现这个......是否有可能或者有更好/更快的方法来做到这一点?

我接受任何意见或建议

我的代码:

<?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

使用 AJAX 调用编辑代码:

@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
});

在 table 中创建一个表单并在 select 中创建一个自定义函数 (我假设您想使用 select 更改它) <select onchange="$.fn.myFunction(this.form)">

之后你想创建一个这样的 ajax 请求:

$.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 );
    }
  });
}