Strange server errors posting an Ajax form

I just wrestled with getting a form to post via ajax. I have done this before but had a bunch of issues crop up this time including strange intermitten server errors that only seemed to occur on Firefox. I resolved it by using the extremely handy YUI connection manager ’setForm’ function to process the data for me. I also found a problem when submitting a non-rails created form that caused an ctionController::InvalidAuthenticityToken error.

I was sending the form by using a javascript function to get each field, concatonate a url (using escape) and use the YUI connection manager with a GET method. This caused intermitten errors on firefox including one like ‘the server did not understand the request’ (or something like that). What was happening was the escape was creating a series of chars that triggered a mod_security rule. The rule was blocking access to the rails server.

ModSecurity: Access denied with code 400 (phase 2). Pattern match "%0[ad]” at REQUEST_URI. [id "950910"] [msg "HTTP Response Splitting Attack. Matched signature <%0a>"] [severity "ALERT"] [hostname "dev.removed.com"] [uri "/aSubmitContact?name=john%20johnson&email=john@removed.com&phone=123455&msg=this%20is%20a%20test%0Athsi%20is%20only%20a%20test&subject=general"]

I did some digging and discovered that YUI has a sweet function to fetch, prepare and send the form fields for me:

Connection Manager can automatically harvest HTML form data and prepare it for either a GET or POST request via the setForm method. When you call this method before initiating the transaction, Connection Manager constructs a GET querystring or a POST message from the form and submits it to the specified URL.

You simply hand the element to YAHOO.util.Connect.setForm(formObject, true); and the connection manager takes care of the rest. SWEET!

After that, another issue came up with rails. It seems that rails expects you to utilize it’s built-in form generator. When I submitted the form I built with javascript using the DOM, I got the error:

ActionController::InvalidAuthenticityToken

This appears to be due to a new feature in rails that attempts to stop cross-site-scripting by attaching an hidden identifier value to the form. I had to disable the feature for my javascript created form. To disable it I used:
protect_from_forgery :only => [:update, :delete, :create].
I realize that it is a nice feature, but it would be nice to see it as optional instead of default.

Tags: , , , ,

Leave a Reply

You must be logged in to post a comment.