Datatables server-side Processing with Sweet Alert 2

Asked

Viewed 448 times

0

I am using Datatables with server-side Processing and using Sweetalert2 to confirm before deleting the record. Everything is working except the Sweet Alert that is not displayed when clicking the delete link.

Using datatables without ajax, Sweet Alert works normally. By clicking on <a class="dropdown-item sa-warning" style="cursor:pointer;" data-route="services/delete/' . $service->id . '"> where the sa-Warning class is, it should call the Sweet Alert script, but nothing happens and there is no error.

View

@extends('layouts.app')
@section('title', 'Serviços')
@push('styles')
<link href="{{ asset('plugins/datatables/dataTables.bootstrap4.min.css') }}" rel="stylesheet" type="text/css"/>
<link href="{{ asset('plugins/datatables/buttons.bootstrap4.min.css') }}" rel="stylesheet"
      type="text/css"/>
@endpush
@section('content')
<div class="row">
    <div class="col-12">
        <div class="card-box table-responsive">
            <div class="col-12 mb-3">
                <a href="{{ route('services.create') }}" class="btn btn-custom waves-light waves-effect">Novo</a>
            </div>
            <table id="datatable" class="table table-bordered">
                <thead>
                <tr>
                    <th>Nome</th>
                    <th style="width: 5%">Ações</th>
                </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>
@endsection
@push('scripts')
<script src="{{ asset('plugins/datatables/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/dataTables.bootstrap4.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/dataTables.buttons.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.bootstrap4.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/jszip.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/pdfmake.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/vfs_fonts.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.html5.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.print.min.js') }}"></script>
<script type="text/javascript">"use strict";
    $(document).ready(function () {
        $('#datatable').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                "method": "POST",
                "url": "{{ route('services.ajax.datatables') }}",
                "dataType": "json"
            },
            "columns": [
                {"data": "name"},
                {"data": "actions", "searchable": false, "orderable": false}
            ]
        });
    });
</script>
@endpush

Sweet Alert

    $('.sa-warning').click(function () {
        $(this).each(function(){
            var route = $(this).data("route");
            swal({
                title: 'Você quer apagar o registro?',
                text: "Está ação não pode ser desfeita!",
                type: 'warning',
                showCancelButton: true,
                confirmButtonClass: 'btn btn-confirm mt-2',
                cancelButtonClass: 'btn btn-cancel ml-2 mt-2',
                cancelButtonText: 'Cancelar',
                confirmButtonText: 'Apagar!'
            }).then(function () {
                $.ajax({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    type: 'DELETE',
                    url: route,
                    success:function(response){
                        window.location.href = response;
                    },
                    error:function(response){
                        console.log(response);
                    }
                })
            })
        });
    });

Routes

Route::post('services/ajax', 'ServiceController@ajaxDatatables')->name('services.ajax.datatables');
Route::get('services/delete/{service}', 'ServiceController@destroyServiceDatatables')->name('services.delete.datatables');

Servicecontroller

namespace App\Http\Controllers;

use App\Service;
use App\Http\Requests\ServiceRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class ServiceController extends Controller
{
public function index()
{
    $services = Service::all();
    return view('service.index')
        ->with('services', $services);
}

public function ajaxDatatables(Request $request)
{
    $columns = [
        0 => 'name',
    ];

    $totalData = Service::count();
    $limit = $request->input('length');
    $start = $request->input('start');
    $order = $columns[$request->input('order.0.column')];
    $dir = $request->input('order.0.dir');

    if (empty($request->input('search.value'))) {
        $services = Service::offset($start)
            ->limit($limit)
            ->orderBy($order, $dir)
            ->get();
        $totalFiltered = Service::count();
    } else {
        $search = $request->input('search.value');
        $services = Service::where('name', 'like', "%{$search}%")
            ->offset($start)
            ->limit($limit)
            ->orderBy($order, $dir)
            ->get();
        $totalFiltered = Service::where('name', 'like', "%{$search}%")
            ->count();
    }

    $data = [];

    if ($services) {
        foreach ($services as $service) {
            $nestedData['name'] = $service->name;
            $nestedData['actions'] = '<div class="btn-group dropdown">
                                <a href="javascript: void(0);"
                                   class="table-action-btn dropdown-toggle arrow-none btn btn-light btn-sm"
                                   data-toggle="dropdown"
                                   aria-expanded="false">
                                    <i class="mdi mdi-dots-horizontal"></i>
                                </a>
                                <div class="dropdown-menu dropdown-menu-right">
                                    <a class="dropdown-item" href="services/' . $service->id . '/edit">
                                        <i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Editar</a>
                                    <a class="dropdown-item sa-warning" style="cursor:pointer;"
                                       data-route="services/delete/' . $service->id . '">
                                        <i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Excluir</a>
                                </div>
                            </div>';
            $data[] = $nestedData;
        }
    }

    $jsonData = [
        "draw" => intval($request->input('draw')),
        "recordsTotal" => intval($totalData),
        "recordsFiltered" => intval($totalFiltered),
        "data" => $data
    ];

    echo json_encode($jsonData);
}

public function create()
{
    return view('service.create');
}

public function store(ServiceRequest $request)
{
    $service = Service::create($request->all());
    Session::flash('alert-success', 'Serviço incluído com sucesso!');
    return redirect()->route('services.index');
}

public function edit(Service $service)
{
    return view('service.edit')
        ->with('service', $service);
}

public function update(ServiceRequest $request, Service $service)
{
    $service->update($request->all());
    Session::flash('alert-success', 'Serviço alterado com sucesso!');
    return redirect()->route('services.index');
}

public function destroy(Service $service)
{
    if ($service->orders->count() > 0) {
        Session::flash('alert-warning', 'Existem orçamentos com esse serviço!');
        return response(route('services.index'));
    } else {
        $service->delete();
        Session::flash('alert-success', 'Serviço excluído com sucesso!');
        return response(route('services.index'));
    }
}

public function destroyServiceDatatables(Service $service)
{
    $service->delete();
    Session::flash('alert-success', 'Serviço excluído com sucesso!');
    return redirect()->route('services.index');
}
}

1 answer

1


I was able to solve the problem by modifying the first line of Sweet Alert from:

$('.sa-warning').click(function () {

for:

$("#datatable").on("click", ".sa-warning", function () {

Browser other questions tagged

You are not signed in. Login or sign up in order to post.