Ad

Ajax To Delete A Record From Database Does Not Fire Redirect In Laravel

- 1 answer

I am deleting a record from my database using an ajax request. This works and deletes the record however then it does not redirect the user with the success message.

I am using a sweetalert modal to display the confirm delete button and when you click yes, the modal goes away and the record has been deleted but the page does not redirect and the record does not disappear until you refresh the page.

This seems to be ignored -

return redirect()->route('users.index')->with('success', 'User deleted!');

AJAX -

<script>
 $(document).ready(function() { 
  $(".swal2-confirm").click(function(){
    var id = '{{ request()->delete_id }}';
    var route = '{{ request()->route }}';
    $.ajax({
      type:'post',
      url:'/admin/' + route + '/' + id,
      dataType: 'json',
      headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
      data: {'_method':'delete', "_token": "{{ csrf_token() }}", id:id},
    });
  });
});
</script>

Controller -

public function destroy($id)
    {
      //Delete user from database
      User::find($id)->delete();

      return redirect()->route('users.index')->with('success', 'User deleted!');
    }
Ad

Answer

I have figured it out by showing the alert and then reloading the page within my ajax -

<script>
$(document).ready(function () {
  $(".swal2-confirm").click(function () {
    var id = '{{ $delete_id }}';
    $.ajax({
      type: 'post',
      url: '/admin/users' + '/' + id,
      dataType: 'json',
      headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
      data: { '_method': 'delete', "_token": "{{ csrf_token() }}", id: id },
      complete: function () {
        swal.fire({
          type: 'success',
          title: 'User Deleted!',
          showConfirmButton: false,
          timer: 2500
        });
        setTimeout(function () { window.location.replace('/admin/users') }, 2500);
      }
    });
  });
});
</script>
Ad
source: stackoverflow.com
Ad