-
-
Save soufianeEL/3f8483f0f3dc9e3ec5d9 to your computer and use it in GitHub Desktop.
/* | |
Exemples : | |
<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() { | |
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) { | |
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; | |
} | |
// Allow user to optionally provide data-confirm="Are you sure?" | |
if ( link.data('confirm') ) { | |
if ( ! laravel.verifyConfirm(link) ) { | |
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': link.data('token') | |
}); | |
var hiddenInput = | |
$('<input>', { | |
'name': '_method', | |
'type': 'hidden', | |
'value': link.data('method') | |
}); | |
return form.append(token, hiddenInput) | |
.appendTo('body'); | |
} | |
}; | |
laravel.initialize(); | |
})(); |
Thanks! 👍
Hi all,
i've change a little bit to support jQuery promise so you can use any confirm action like bootbox or swal 👍
https://gist.github.com/ghprod/0bb7f8d207ba7838a0e6
Thanks
Thanks! 👍
Got a problem with this. I get redirected to the href
link and doesn't trigger the events registered above. However when I do debug console and traverse through the handleMethod
it submits fine. Should I place this inside $(function(){})
?
It's actually triggering the handleMethod
method. However, the reason for the redirection was because the e.preventDefault()
wasn't triggered so the link automatically redirects without calling the form.submit()
first.
thanks its work!
Cool! 👍
Doesn't work for me, redirects to view method
Same here, doesn't work for me redirecting to view.
Great, thanks for the update :)
no idea why, but doesn't work :(
Nice job ;)