I have code like the following ( it’s a remote form )
def something
@user = User.find_by_email(params[:email])
@success = true
@error = nil
if !@user
@success = false
@error = "No such user"
elsif !@user.some_condition
@success = false
@error = "User did not pass condition"
end
respond_to do |format|
format.json { render "my_json_view",:status => @success ? 200 : 403 }
end
end
In the my_json_view I do something like:
json.response do |json|
if @success
json.success true
# data I need here
else
json.success false
json.error @error
end
end
This way, I can easily hook into the ajax:error event, and easily handle the error case. I’m just wondering how good practice this is. Is it ok to return a different http code, so that jQuery will know there was a failure?
Sure. That’s what error codes are for. But make sure you choose a proper HTTP status code.