Created
December 12, 2012 07:01
-
-
Save the-teacher/4265679 to your computer and use it in GitHub Desktop.
Building Valid Rails Form with csrf token via JQuery (JavaScript, CoffeeScript)
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
$.rails.form_build = (url = '#', method = 'get', opts = {}) -> | |
_method = '' | |
method = method.toLowerCase() | |
# csrf | |
csrf_token = $('meta[name=csrf-token]').attr('content') | |
csrf_param = $('meta[name=csrf-param]').attr('content') | |
# build options | |
_opts = '' | |
_opts += " #{k}=#{v}" for k, v of opts | |
# method addons | |
if ['post', 'patch', 'put', 'update', 'delete'].indexOf(method) > -1 | |
if method isnt 'post' | |
_method = "<input type='hidden' value='#{method}' name='_method'>" | |
method = 'post' | |
else | |
method = 'get' | |
# view | |
$ """ | |
<form action='#{url}' method='#{method}' #{_opts} accept-charset='UTF-8'> | |
<div style='margin:0;padding:0;display:inline'> | |
#{ _method } | |
<input type='hidden' value='✓' name='utf8'> | |
<input type='hidden' value='#{ csrf_token }' name='#{ csrf_param }'> | |
</div> | |
</form> | |
""" | |
$.rails.form_submit = (f) -> f.hide().appendTo('body').submit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment