2016-02-07 2 views
0

Я пытаюсь удалить строку в db с помощью Jquery/Ajax.DELETE с AJAX (JQuery) не работает с Laravel 5.2

Я следил за this thread, но я не могу заставить его работать.

Вот мое мнение:

@foreach($tournaments as $tournament) 
<tr id="line" data-id="{{$tournament->id}}"> 
    <td> 
     <a href="{!! URL::action('[email protected]', $tournament->id) !!}">{{ $tournament->id }}</a> 
    </td> 

    <td>{{ $tournament->owner->name}}</td> 
    <td class="text-center"> 
     {!! Form::open(['method' => 'DELETE', 'id' => 'formDeleteTourament', 'action' => ['[email protected]', $tournament->id]]) !!} 
     {!! Form::button('<i class="glyphicon glyphicon-remove"></i>', ['class' => 'btn text-warning-600 btn-flat btnDeleteTournament', 'data-id' => $tournament->id ]) !!} 
     {!! Form::close() !!} 
    </td> 
</tr> 

@endforeach 

<script> 
    $(function() { 
     $('#.tnDeleteTournament').on('click', function (e) { 
      var inputData = $('#formDeleteTourament').serialize(); 
      var dataId = $('.btnDeleteTournament').attr('data-id'); 
      console.log(inputData); // displays: _method=DELETE&_token=tGFhaAr5fVhDXEYL3SaXem3WaTNJlSdFEkaVDe9F 

      console.log(dataId); // displays 1 
      var $tr = $(this).closest('tr'); 

      swal({ 
       title: "Are you sure?", 
       text: "You will not be able to recover this Tournament!", 
       type: "warning", 
       showCancelButton: true, 
       confirmButtonColor: "#EF5350", 
       confirmButtonText: "Yes, delete it!", 
       cancelButtonText: "No, cancel pls!", 
       closeOnConfirm: false, 
       closeOnCancel: false 
      }, 
      function (isConfirm) { 
       if (isConfirm) { 
        e.preventDefault(); 

        $.ajax(
         { 
          type: 'POST', // I tried with DELETE too 
          url: '{{ url('/tournaments/') }}' + dataId, 
          data: inputData, 
          success: function (msg) { 
           console.log('success'); // It triggers! 
           $tr.find('td').fadeOut(1000, function() { 
            $tr.remove(); 
           }); 
           swal({ 
            title: "Deleted!", 
            text: "Tournament has been deleted.", 
            confirmButtonColor: "#66BB6A", 
            type: "success" 

           }); 

          }, 
          error: function() { 
           swal("Oops", "We couldn't connect to the server!", "error"); 
          } 
         } 
        ) 


       } 
       else { 
        swal({ 
         title: "Cancelled", 
         text: "Your Tournament is safe :)", 
         confirmButtonColor: "#2196F3", 
         type: "error" 
        }); 
       } 
      }); 
     }); 
    }); 

Вот мой Контроллер илит:

public function destroy(Tournament $tournament) 
{ 
    $tournament->delete(); 
    return response(['msg' => 'Product deleted', 'status' => 'success']); 


} 

Раньше у меня было работать без AJAX поэтому маршрут OK.

все работает отлично (модальности шоу), но не удаляет мой турнир

Я новичок в JS/JQuery, так что я не знаю, что происходит.

Любая идея, как исправить это?

+1

Наверно потому, что у вас есть идентификатор, который повторяется. Идентификационные значения должны быть уникальными, иначе только первый экземпляр будет работать правильно. – Rasclatt

+0

aaaah ok. Как его исправить? –

+0

Вы можете автоинкрементять свои идентификаторы для одного или использовать класс вместо селектора. – Rasclatt

ответ

0

Вы должны в значительной степени изменить все свои ссылки на использование class в качестве селектора. Я только гадать, на вещи Laravel, а также сделать свой идентификатор уникальной (я добавил турнир Id), но все это должно измениться в class:

Гадание на это, не знакомы с синтаксисом

@foreach($tournaments as $tournament) 
<tr id="line{{$tournament->id}}" data-id="{{$tournament->id}}" class="parentTr"> 
    <td> 
     <a href="{!! URL::action('[email protected]', $tournament->id) !!}">{{ $tournament->id }}</a> 
    </td> 

    <td>{{ $tournament->owner->name}}</td> 
    <td class="text-center"> 
     {!! Form::open(['method' => 'DELETE', 'class' => 'formDeleteTourament', 'action' => ['[email protected]', $tournament->id]]) !!} 
     {!! Form::button('<i class="glyphicon glyphicon-remove"></i>', ['class' => 'btn text-warning-600 btn-flat btnDeleteTournament', 'data-id' => $tournament->id ]) !!} 
     {!! Form::close() !!} 
    </td> 
</tr> 

@endforeach 

Javascript Изменения

<script> 
$(function() { 
    $('.btnDeleteTournament').on('click', function (e) { 
     var inputData = $(this).parents('.formDeleteTourament').serialize(); 
     var dataId  = $(this).data('id'); 
     var $tr   = $(this).closest('tr'); 
     swal({ 
      title: "Are you sure?", 
      text: "You will not be able to recover this Tournament!", 
      type: "warning", 
      showCancelButton: true, 
      confirmButtonColor: "#EF5350", 
      confirmButtonText: "Yes, delete it!", 
      cancelButtonText: "No, cancel pls!", 
      closeOnConfirm: false, 
      closeOnCancel: false 
     }, 
     function (isConfirm) { 
      if (isConfirm) { 
       e.preventDefault(); 
       $.ajax({ 
         // I don't you know if you have to escape the inner 
         // quotes or not, that is a framework syntax thing 
         url: '{{ url('/tournaments/') }}', 
         type: 'POST', 
         // Just include the id in a post data object 
         data: { form: inputData, id: dataId }, 
         success: function (msg) 
          { 
           console.log(msg); 
           $tr.find('td').fadeOut(1000, function() { 
            $tr.remove(); 
           }); 

           swal({ 
            title: "Deleted!", 
            text: "Tournament has been deleted.", 
            confirmButtonColor: "#66BB6A", 
            type: "success" 

           }); 

          }, 
         error: function() 
          { 
           swal("Oops", "We couldn't connect to the server!", "error"); 
          } 
        }); 
      } 
      else { 
       swal({ 
        title: "Cancelled", 
        text: "Your Tournament is safe :)", 
        confirmButtonColor: "#2196F3", 
        type: "error" 
       }); 
      } 
     }); 
    }); 
}); 
</script> 
Смежные вопросы