Szymon Jabłoński Szymon Jabłoński - 1 year ago 75
jQuery Question

Ajax DELETE redirects even if prevented

I'm trying to delete row from database with DELETE method and using AJAX in my Laravel 5.2 project. Everything is working, picture is deleted from server and the row is deleted from database but after deleting it redirects to JSON response.

My controller's action:

public function deletePhoto(Photo $photo)
if ($photo->delete()) {
unlink('files/' . $photo->filename);
unlink('files/thumbs/' . $photo->filename);

return response()->json(['result' => 0]);

return response()->json(['result' => 1]);

It works this way while adding photos (it adds but doesn't redirect).

Here is my ajax code:

$('#deleteForm').submit(function(e) {
var currentElement = $(this);
var formUrl = $(this).attr('action');

type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');


return false;

I tried many changes (from laracast and stackoverflow) with method, token and data but nothing worked.

How do I solve this problem?

Answer Source

Add a prevents defaults to your submit event. The page is redirecting because you're initiating a submit event.


Change Submit event to:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download