Rails Form Authenticity Token with Ajax (Defensive Enhancement)
When sending POST through ajax with form security turned on with Rails can sometimes be a pain in the butt. However if you plan for your users to be able to do the same task without javascript, adding the Ajax goodness unobtrusively is a cinch and we still get the benefits of the authenticity token. The example below is a simple form for a post. But Rails will automatically set the security token in the form plus the correct method to use for the object (POST or PUT). So if we didn’t have javascript enabled this form would work without a problem. With JS enabled, we can use a convenience method from prototype JS library to serialize the form which includes the title of the post but the authenticity token as well.
<%- form_for @post, :id => 'post_form' do |f| -%>
<div>
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<%= f.submit, :id => 'submit' %>
<%- end -%>
<script type="text/javascript" charset="utf-8">
document.observe('dom:loaded',function(){
// Remove button
$('submit').hide()
var form = $('post_form')
// As you tab out or click somewhere else it
// submits via Ajax
$('post_title').observe('blur', function(ev){
new Ajax.Request(form.action, {
// IMPORTANT PART
parameters: form.serialize(),
onSuccess: function(transport) {
alert('Success')
},
onFailure: function(transport) {
alert('Failure')
}
})
})
})
</script>
The script does a few interesting things in addition to the submitting the authenticity token. For example it will remove the submit button and an event listener to see when focus leaves the text box to post the form via AJax. This allows users to browsers that can not interpret JS to still work but gives added benefits to the browsers that can use javascript.