Skip to content

Instantly share code, notes, and snippets.

@lapin-b
Created March 9, 2016 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lapin-b/1ecb5df2d16bfed9f92a to your computer and use it in GitHub Desktop.
Save lapin-b/1ecb5df2d16bfed9f92a to your computer and use it in GitHub Desktop.
Spoofs a request method for RESTful controllers
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var links = document.querySelectorAll('a[data-method]');
var csrf = document.querySelector('meta[name=csrf]').content; // Change if needed
var body = document.querySelector('body');
// Spoof delete method
// USAGE: <a href="..." data-method="<method>">...</a>
Array.prototype.forEach.call(links, function(link){
// Create form
var form_id = 'l-form-' + getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
var form = document.createElement('form');
form.id = form_id;
form.method = 'POST';
form.action = link.href;
var csrf_token = document.createElement('input');
csrf_token.name = '_token';
csrf_token.type = 'hidden';
csrf_token.value = csrf;
var method = document.createElement('input');
method.name = '_method';
method.type = 'hidden';
method.value = link.getAttribute('data-method').toUpperCase();
form.appendChild(csrf_token);
form.appendChild(method);
link.setAttribute('onclick', 'document.querySelector("#'+ form_id +'").submit(); return false;'); // Not the cleanest JS ever
body.appendChild(form);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment