Skip to content

Instantly share code, notes, and snippets.

@hakankozakli
Forked from JeffreyWay/laravel.js
Last active February 11, 2018 23:24
Show Gist options
  • Save hakankozakli/3b76daa8cb49193f366178b98b64b71d to your computer and use it in GitHub Desktop.
Save hakankozakli/3b76daa8cb49193f366178b98b64b71d to your computer and use it in GitHub Desktop.
Want to send a DELETE request when outside of a form? This will handle the form-creation bits for you dynamically, similar to the Rails implementation. (Requires jQuery, but doesn't have to.)To use, import script, and create a link with the `data-method="DELETE"` attribute.
/*
<a href="posts/2" data-method="delete"> <---- We want to send an HTTP DELETE request
- Or, request confirmation in the process -
<a href="posts/2" data-method="delete" data-confirm="Are you sure?">
*/
(function(window, $, undefined) {
var Laravel = {
initialize: function() {
$(function(){
$(document).on('click', 'a[data-method]', function(e){
e.preventDefault()
var link = $(this)
var httpMethod = link.data('method').toUpperCase()
var form
if ($.inArray(httpMethod, ['PUT', 'PATCH', 'POST', '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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment