-
-
Save jhechavarria/8c2df8785160ec59be8e6053462180e8 to your computer and use it in GitHub Desktop.
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
jQuery(function () { | |
var larails = { | |
// Define the name of the hidden input field for method submission | |
methodInputName: '_method', | |
// Define the name of the hidden input field for token submission | |
tokenInputName: '_token', | |
// Define the name of the meta tag from where we can get the csrf-token | |
metaNameToken: 'csrf-token', | |
initialize: function() | |
{ | |
$('a[data-method]').on('click', this.handleMethod); | |
}, | |
handleMethod: function(e) | |
{ | |
e.preventDefault(); | |
var link = $(this), | |
httpMethod = link.data('method').toUpperCase(), | |
confirmMessage = link.data('confirm'), | |
confirmTag = link.data('confirm-btn'), | |
confirmButton = $(confirmTag), | |
cancelTag = link.data('cancel-btn'), | |
cancelButton = $(cancelTag), | |
form; | |
// Exit out if there is no data-methods of PUT, PATCH or DELETE. | |
if ($.inArray(httpMethod, ['PUT', 'PATCH', 'DELETE']) === -1) | |
{ | |
return; | |
} | |
// Allow user to optionally provide data-confirm-btn="#query-selector" and data-cancel-btn="#query-selector" | |
if (confirmTag && confirmButton.length) | |
{ | |
confirmButton.on('click', function(){ | |
form = larails.createForm(link); | |
form.submit(); | |
}); | |
if (cancelTag && cancelButton.length) | |
{ | |
cancelButton.on('click', function() { | |
confirmButton.off('click'); | |
}); | |
} | |
} | |
// Allow user to optionally provide data-confirm="Are you sure?" | |
else if (confirmMessage) | |
{ | |
if( confirm(confirmMessage) ) { | |
form = larails.createForm(link); | |
form.submit(); | |
} | |
} else { | |
form = larails.createForm(link); | |
form.submit(); | |
} | |
}, | |
createForm: function(link) | |
{ | |
var token = link.data('token'); | |
if (!token) | |
token = $('meta[name=' + larails.metaNameToken + ']').prop('content'); | |
var form = $('<form>', | |
{ | |
'method': 'POST', | |
'action': link.prop('href') | |
}); | |
var token = $('<input>', | |
{ | |
'type': 'hidden', | |
'name': larails.tokenInputName, | |
'value': token | |
}); | |
var method = $('<input>', | |
{ | |
'type': 'hidden', | |
'name': larails.methodInputName, | |
'value': link.data('method') | |
}); | |
return form.append(token, method).appendTo('body'); | |
} | |
}; | |
larails.initialize(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment