Fixing JangoSteve's rails.js form callback example
Think of this as a working example made from his code samples.
Scenario or Expected User Story gone wrong
Here's what happens out of the box:
- Submit form with
:remote => trueenabled,
- validate user input.
- For valid user input,
create.js.erbwith jQuery instructions to insert the object's content into the page DOM, and
- pass a HTTP status code of 201 Created along.
- For invalid user input,
create.js.erbwith jQuery instructions to build error messages, and
- pass a HTTP status code of 400 Bad Request or 424 Unprocessable Entity because it's the right thing to do, as you know very well.
- For valid user input,
- Continue using the web app/web service, whatever.
Fixing the problem
Giving up the HTTP 4xx status codes isn't an option. We really shouldn't give in to
As JangoSteve clearly instructed us, the current jQuery UJS driver supports the following four event callbacks:
ajax:beforeSend ajax:success ajax:complete ajax:error
Turns out HTTP response 400 triggers
ajax:error instead of
ajax:success results in the XMLHttpRequest's (XHR) response body's execution (or rather:
eval XHR's response on
- Author's website: http://christiantietze.de/
- Author's twitter: @divinedominion
- Steve Schwartz' excellent blog: http://www.alfajango.com/blog/
Tested for and crafted using Ruby 2.0.0, Rails 3.2.13.
(The MIT License)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.