I've got in-place editing on a page in my app (using Rails 2.3.5 and jQuery). I want to know how to display an error on the page when the update fails.
I'm using ajax (an XMLHttpRequest) to save an update to a Comment object. The controller has an update method like this:
def update
@comment = Comment.find(params[:id])
respond_to do |format|
# if @comment.update_attributes!(params[:comment])
if false #deliberately forcing a fail here to see what happens
format.json { render :nothing => true }
else
format.json { render :json => @comment.errors, :status => :unprocessable_entity }
end
end
end
In Firebug, I can see the server returns a "422" (an appropriate validation error status code). But it's a response to an XMLHttpRequest so there is no redirect to an error page.
I think I actually want to do this:
format.json { render :json => @comment.errors}
or maybe this:
format.json {render :json => { :status => :error, :message => "Could not be saved" }.to_json, :status => 400 }
and trigger some Javascript function that iterates through (and displays) any errors.
I'm using a rails plugin REST in Place to implement the in-place editing. It doesn't appear to have any callback function to handle a failure. What are my options? Can I write some Javascript to respond to a failure condition without hacking the plugin? Do I have to hack the rest_in_place plugin to handle a failure condition? Is there a better plugin (for Rails or jQuery) that handles in-place editing, including failure conditions?
UPDATE
This post from Peter Bui Standard JSON Response for Rails and jQuery was helpful in showing how to handle an error message from the server using XMLHttpRequest.status
. I looked at his implementation of a blog using ajax paydro-talks. I'm surprised at the complexity required to handle a simple error condition. Usually Rails has all the goodness baked in but it seems server errors with JSON are out of scope. Can that be?
I also looked at grimen's validatious-on-rails which accommodates models validations when ajax XMLHttpRequest is used. It's not clear to me how I'd use it to handle the general case of a "save" failing when validations succeed.
I think your best option might be to just hack the plugin in this case, as it is really stupid that the plugin doesn't have an error handler anyway. hint: maybe tell the author of the plugin that it would be nice and useful to handle errors (what if connection fails or anything?? plugin will never know and no feedback for user).
It should suffice if you add something like this around line 33 in jquery.rest_in_place.js
after the success option
"error": function(xhr, state, error) {
//do error handling here e.g.
alert(state);
//or $.parseJSON(xhr.responseText) and whatever or similar
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With