Rails Form Authenticity Token in Javascript

December 15th, 2007 10 Comments »

Hey guys, just a basic little snippet to get and encode the form authenticity token new in Rails 2.0, but in Javascript.

var AJ = {
  encode_authenticity_token:function(token) {
    return encodeURIComponent($(token).value)
  },

  authenticity_token_query_parameter_for_page:function() {
    return 'authenticity_token=' + AJ.encode_authenticity_token(document.body.select('input[name="authenticity_token"]')[0])
  },

  ajax_request:function(url) {
    new Ajax.Request(url, {asynchronous:true, evalScripts:true, parameters:AJ.authenticity_token_query_parameter_for_page()})
  }
}

You can call AJ.ajax_request(url) to do a rails-style link_to_remote post and execute, or just get the form authenticity token in a format ready for the query string by using AJ.authenticity_token_query_parameter_for_page()

Hope this is helpful!