Skip to content

Instantly share code, notes, and snippets.

@hakankozakli

hakankozakli/laravel.js

Forked from JeffreyWay/laravel.js
Last active Feb 11, 2018
Embed
What would you like to do?
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
You can’t perform that action at this time.