Delete record with Laravel via AJAX

Asked

Viewed 1,121 times

1

I am developing an application in PHP with Laravel and I have in my Alunoscontroller and following method:

public function destroy($id)
{
    $aluno = new Aluno();
    $result = $aluno->find($id)->delete();

    if($result)
        return redirect()->back();
    else
        return 'Falha';
}

So far so good, the function works correctly. The problem is that I decided to use Sweetalert to make my confirm before deletion. It looked like this:

var btnExcluir = $('.btn-danger');
btnExcluir.click(function(event){
    event.preventDefault();
    swal({
        title: "Deseja continuar?",
        text: "O cadastro do aluno será excluído permanentemente!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Sim, excluir!",
        cancelButtonText: "Cancelar",
        closeOnConfirm: false
    }, function(){
        $.ajax({
            url: "/alunos/destroy",
            type: "POST",
            data: {
                id: 8
            },
            dataType: "html",
            success: function () {
                swal("Excluído!", "O cadastro do aluno foi excluído com sucesso.", "success");
            }, error: function(){
                swal("Erro!", "Não foi possível remover o aluno.", "error");
            }
        });
    });
});

I passed the fixed id 8 just for testing with a record I have but it is always falling into error.

I tried to pass the id in the url, tried to use type DELETE, tried to pass ID_ALUNO_ALU (which is the name of the attribute in the database and model) in date instead of id and nothing worked. Someone who’s used AJAX on Laravel could give me a light?

In advance, the interesting part of my view is like this:

@foreach($alunos as $aluno)
<tr>
    <td>{{$aluno['NM_NIS_ALU']}}</td>
    <td>{{$aluno['ST_NOME_ALU']}}</td>
    <td class="text-right">{{$aluno['IDADE']}}</td>
    <td class="text-center">
        {!! Form::open(['route' => ['alunos.destroy', $aluno['ID_ALUNO_ALU']], 'method' => 'delete', 'class' => 'form']) !!}
            <button type="button" class="btn btn-warning btn-xs esconder-acao" data-toggle="modal" data-target="#modalAluno{{$aluno['ID_ALUNO_ALU']}}">Editar</button>
            {!! Form::submit('Excluir', ['class' => 'btn btn-danger btn-xs esconder-acao']) !!}
        {!! Form::close() !!}
    </td>
</tr>
@endforeach

How do I pass student id to js?

Thank you guys!

  • Try changing dataType: "html" to dataType: "JSON"

  • "but it’s always falling into error" that in Javascript, right? And in PHP, what happens? The record is properly deleted from the database?

  • Do not delete no. I found that the date is not coming in Stroy, but still do not know why

2 answers

0

You have probably defined in your route file the verb "delete" for the specific route, since in your form you have defined this method. When you perform the action in Ajax, the request is going as post. If there is no post waiting on this route, you will receive a route error not found. Change dataType to JSON and the request method to "delete".

Laravel has a feature to work with "unofficialized" HTTP verbs, which is to put a hidden field with the name _method in the form, to work with DELETE methods, for example. Do the same in the data field of your request.

  • The author specifies that he tried to use type: "delete" in the AJAX request. This is what you are suggesting?

  • In addition to putting the type: "delete", put a _method key: "delete", which is the default form that Laravel handles forms that use this verb and others, such as PUT

  • I’ve tried all this already. I’m using a Controller Resource so my route is Resource too

0

You made 3 mistakes: the AJAX request URL is wrong because it must contain the segment relating to the student ID; you are not informing the key _method with the value DELETE in the object data; the dataType that you hope to receive is of the type json and not html. There is also no need to inform the student ID on the date object if this information will already be contained in the URL and the use of the event click in the items having the class .btn-danger was a bad choice since it only makes it difficult to obtain the form data.

$('.form-aluno-delete').on('submit', function(e) {
    e.preventDefault();

    $.ajax({
        url: $(this).attr('url'),
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function () {
            swal("Excluído!", "O cadastro do aluno foi excluído com sucesso.", "success");
        }, error: function(){
            swal("Erro!", "Não foi possível remover o aluno.", "error");
        }
    });
});

});

@foreach($alunos as $aluno)
<tr>
  <td>{{$aluno['NM_NIS_ALU']}}</td>
  <td>{{$aluno['ST_NOME_ALU']}}</td>
  <td class="text-right">{{$aluno['IDADE']}}</td>
  <td class="text-center">
    {!! Form::open(['route' => ['alunos.destroy', $aluno['ID_ALUNO_ALU']], 'class' => 'form-aluno-delete']) !!}
      <input type="hidden" name="_method" value="DELETE"> 
      <button type="button" class="btn btn-warning btn-xs esconder-acao" data-toggle="modal" data-target="#modalAluno{{$aluno['ID_ALUNO_ALU']}}">Editar</button>
      {!! Form::submit('Excluir', ['class' => 'btn btn-danger btn-xs esconder-acao']) !!}
    {!! Form::close() !!}
</td>
</tr>
@endforeach
  • There is a need for the input with the name _mthod only if you use the submit form, no? If used AJAX, the method can be set directly as DELETE, since jQuery supports such a method.

  • No, this field is necessary, because it is this information that will tell Laravel to use the DELETE method instead of POST when searching for the corresponding route. You can also delete this field and pass this information directly to the key data in the ajax request options.

  • That’s exactly what I said xD

  • Yes, sorry! If you pass directly on the key method you will not need the field in the view, but you will probably need the field csrf_token that I forgot to put on, unless I’ve disabled that middleware.

Browser other questions tagged

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