var token = $('new_post').authenticity_token.value;
var post = new Request({url:this.getParent().getParent().getElementsByTagName('form')[0].action}).send('authenticity_token='+token+'&post[content]='+this.value);
Rails generates the authenticity token using the SecureRandom.base64 method provided by ActiveSupport to generate a random string. Unfortunately Base64 strings cannot be used directly in URLs because they contain ‘+’, ‘/’ and ‘=’ characters and it was this that was causing the bug: if the authenticity token contained a ‘+’ then it was being interpreted as an URL encoded space causing the exception to occur. Of course JavaScript provides a nice solution to this problem: the encodeURIComponent method.
You may also have noticed there’s another, potentially nasty, related bug lurking in that seemingly innocent bit of JavaScript: the post[content] parameter isn’t being encoded either. This means that if the user was to enter something like you really should &handle this=properly then the ampersand would be treated as a new parameter rather than part of the content string. Again encodeURIComponent comes to the rescue:
var token = $('new_post').authenticity_token.value;
var post = new Request({url:this.getParent().getParent().getElementsByTagName('form')[0].action}).send('authenticity_token='+encodeURIComponent(token)+'&post[content]='+encodeURIComponent(this.value));


4 comments
Comment on Encode URL parameters in JavaScript by Michael Kintzer
July 9th, 2009 @ 09:14 – permalink
Comment on Encode URL parameters in JavaScript by John
September 12th, 2009 @ 00:14 – permalink
Comment on Encode URL parameters in JavaScript by Rob Anderton
September 13th, 2009 @ 16:28 – permalink
Comment on Encode URL parameters in JavaScript by Tony
January 12th, 2010 @ 21:26 – permalink
Leave a reply
You can use Markdown in your comment as well as plain HTML. You can use
<filter:jscode lang="ruby">and</filter:jscode>tags to surround code blocks (supported languages are css, html, javascript and ruby). Your email address will not be published.If your comment doesn’t appear immediately after posting it could have been marked as spam. Don’t worry: we regularly check for and approve incorrectly filtered comments so you shouldn’t have to wait too long for it to be shown.