Created
January 31, 2014 23:21
-
-
Save clarkf/8745336 to your computer and use it in GitHub Desktop.
Laravel 4 REST Helper without jQuery
This file contains 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
(function (document) { | |
document.addEventListener('DOMContentLoaded', function(){ | |
// Document loaded | |
/** | |
* Listen for click events on elements that have a data-method | |
* attribute. | |
* | |
* This should work on all modern browsers (IE 9+) | |
* | |
* i.e. | |
* <a href="/resource/1" method="delete">Delete Resource</a> | |
*/ | |
document.addEventListener('click', function (e) { | |
var target = e.target; | |
// Detect if the object clicked had a 'data-method' attribute | |
if (target.getAttribute('data-method')) { | |
// Stop the event from propagating | |
e.stopPropagation(); | |
e.preventDefault(); | |
// Create the necessary HTML elements | |
var form = document.createElement('form'), | |
input = document.createElement('input'); | |
// Set the form to POST to the href of the target | |
form.setAttribute('method', 'post'); | |
form.setAttribute('action', target.href); | |
// Set the post value _method to the value of data-method | |
input.setAttribute('type', 'hidden'); | |
input.setAttribute('name', '_method'); | |
input.setAttribute('value', target.getAttribute('data-method')); | |
// Ensure that the form is hidden when appending to DOM | |
form.setAttribute('style', 'display: none'); | |
// Add the input to the form, add the form to the DOM | |
form.appendChild(input); | |
document.body.appendChild(form); | |
// Submit the form | |
form.submit(); | |
// Ensure event doesn't propagate. | |
return false; | |
} | |
}); | |
}); | |
})(window.document); |
This file contains 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
!function(a){a.addEventListener("DOMContentLoaded",function(){a.addEventListener("click",function(b){var c=b.target;if(c.getAttribute("data-method")){b.stopPropagation(),b.preventDefault();var d=a.createElement("form"),e=a.createElement("input");return d.setAttribute("method","post"),d.setAttribute("action",c.href),e.setAttribute("type","hidden"),e.setAttribute("name","_method"),e.setAttribute("value",c.getAttribute("data-method")),d.setAttribute("style","display: none"),d.appendChild(e),a.body.appendChild(d),d.submit(),!1}})})}(window.document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment