-
-
Save fer-ri/0bb7f8d207ba7838a0e6 to your computer and use it in GitHub Desktop.
You use Laravel 5 and you want to send a DELETE request without creating a form? This will handle the form-creation bits for you dynamically, similar to the Rails implementation. To use, import script, and create a link with the `data-method="DELETE"` and `data-token="{{csrf_token()}}"` attributes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Taken from: https://gist.github.com/soufianeEL/3f8483f0f3dc9e3ec5d9 | |
Modified by Ferri Sutanto | |
- use promise for verifyConfirm | |
Examples : | |
<a href="posts/2" data-method="delete" data-token="{{csrf_token()}}"> | |
- Or, request confirmation in the process - | |
<a href="posts/2" data-method="delete" data-token="{{csrf_token()}}" data-confirm="Are you sure?"> | |
*/ | |
(function(window, $, undefined) { | |
var Laravel = { | |
initialize: function() { | |
this.methodLinks = $('a[data-method]'); | |
this.token = $('a[data-token]'); | |
this.registerEvents(); | |
}, | |
registerEvents: function() { | |
this.methodLinks.on('click', this.handleMethod); | |
}, | |
handleMethod: function(e) { | |
e.preventDefault() | |
var link = $(this) | |
var httpMethod = link.data('method').toUpperCase() | |
var form | |
// If the data-method attribute is not PUT or DELETE, | |
// then we don't know what to do. Just ignore. | |
if ($.inArray(httpMethod, ['PUT', 'DELETE']) === -1) { | |
return false | |
} | |
Laravel | |
.verifyConfirm(link) | |
.done(function () { | |
form = Laravel.createForm(link) | |
form.submit() | |
}) | |
}, | |
verifyConfirm: function(link) { | |
var confirm = new $.Deferred() | |
var userResponse = window.confirm(link.data('confirm')) | |
if (userResponse) { | |
confirm.resolve(link) | |
} else { | |
confirm.reject(link) | |
} | |
// bootbox.confirm(link.data('confirm'), function(result) { | |
// if (result) { | |
// confirm.resolve(link) | |
// } else { | |
// confirm.reject(link) | |
// } | |
// }) | |
return confirm.promise() | |
}, | |
createForm: function(link) { | |
var form = | |
$('<form>', { | |
'method': 'POST', | |
'action': link.attr('href') | |
}); | |
var token = | |
$('<input>', { | |
'type': 'hidden', | |
'name': '_token', | |
'value': link.data('token') | |
}); | |
var hiddenInput = | |
$('<input>', { | |
'name': '_method', | |
'type': 'hidden', | |
'value': link.data('method') | |
}); | |
return form.append(token, hiddenInput) | |
.appendTo('body'); | |
} | |
}; | |
Laravel.initialize(); | |
})(window, jQuery); |
thanks..
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I click the cancel button, it still deletes the item. Any idea what might cause that?