Last active
June 12, 2018 07:21
-
-
Save liyu001989/18f94f2642b5f39cbc73b7b8420d2c7f to your computer and use it in GitHub Desktop.
laravel make post or delete method from a <a> link use bootbox
This file contains hidden or 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
require(['jquery', 'bootbox'], function($, bootbox) { | |
/* | |
<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() { | |
var laravel = { | |
initialize: function() { | |
this.methodLinks = $('a[data-method]') | |
this.registerEvents() | |
}, | |
registerEvents: function() { | |
this.methodLinks.on('click', this.handleMethod) | |
}, | |
handleMethod: function(e) { | |
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', 'POST']) === -1) { | |
return | |
} | |
// Allow user to optionally provide data-confirm="Are you sure?" | |
if (link.data('confirm')) { | |
bootbox.confirm(link.data('confirm'), function(result) { | |
if (!result) { | |
return | |
} | |
form = laravel.createForm(link) | |
form.submit() | |
e.preventDefault() | |
}) | |
return false | |
} | |
form = laravel.createForm(link) | |
form.submit() | |
e.preventDefault() | |
}, | |
verifyConfirm: function(link) { | |
return confirm(link.data('confirm')) | |
}, | |
createForm: function(link) { | |
var form = | |
$('<form>', { | |
'method': 'POST', | |
'action': link.attr('href') | |
}) | |
var token = | |
$('<input>', { | |
'type': 'hidden', | |
'name': '_token', | |
'value': $('meta[name="csrf-token"]').attr('content') // hmmmm... | |
}) | |
var hiddenInput = | |
$('<input>', { | |
'name': '_method', | |
'type': 'hidden', | |
'value': link.data('method') | |
}) | |
return form.append(token, hiddenInput) | |
.appendTo('body') | |
} | |
} | |
laravel.initialize() | |
})() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment