Created
June 13, 2014 11:45
-
-
Save fragoulis/0ff3bdfd57eb0ce1074f to your computer and use it in GitHub Desktop.
Enables clients to submit empty POST, PUT and DELETE requests using simple links.
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
(function($) { | |
$(document).on('click', 'a[data-method]', function(e) { | |
e.preventDefault(); | |
var $this = $(this), | |
action = $this.attr('href'), | |
method = $this.data('method') | |
; | |
if (['post', 'put', 'delete'].indexOf(method) < 0) | |
throw 'Binding misused: Unrecognized method "' + method +'"'; | |
// console.debug('action=%s, method=%s', action, method); | |
$form = $('<form action="'+ action +'" method="post"></form>'); | |
if (method === 'put' || method === 'delete') { | |
$form.append('<input type="hidden" name="_method" value="'+ method +'" />'); | |
} | |
$form.appendTo('body').submit(); | |
}); | |
})(window.jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Say you want to delete an object with ID equal to 1 (not with ajax) using something as simple as a link but also conform with the REST principle, which means that the request method should be
DELETE
and the object url should be something likehttp://www.venture.com/api/v1/object/1
Simple usage:
This way you can keep your server side code clean (delete objects only on
DELETE
requests) and also use simple form submission.Also, in case it is not obvious, HTML5
form
does not supportPUT
andDELETE
methods.