0
votes

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!');
    }
1
you should return json response like return response(['url' => route('user.index')], 200) and then in you ajax success part you can do this window.location.href = data.url Salman Zafar
if your using ajax call it will not redirect you to that page, you need to send success status in response of ajax call and then reload page location.reload(); or instead of ajax just simply use url to call delete function so it will work as you written codeSagar Sainkar

1 Answers

1
votes

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>