Datatables server-side processing with Sweet Alert 2

0

I am using Datatables with server-side processing and using SweetAlert2 to confirm before deleting the record. Everything is working except for the sweet alert that is not displayed when you click the delete link.

Using datatables without ajax, sweet alert works fine. When you click on <a class="dropdown-item sa-warning" style="cursor:pointer;" data-route="services/delete/' . $service->id . '"> where you have the sa-warning class, you should call the sweet alert script, but nothing happens and you do not have any errors.

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');
}
}
    
asked by anonymous 03.05.2018 / 17:14

1 answer

0

I was able to solve the problem by modifying the first line of the sweet alert from:

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

To:

$("#datatable").on("click", ".sa-warning", function () {
    
04.05.2018 / 03:39