4

What i want

I use the new rails respond_to Controller Api with a ajax form. If an object does not validate rails returns a Json Error Object and triggers the "ajax:error" event. I want to show each error next/under the corresponding form field (we are using formatastic).

Here my Example..

controller:

class Admin::PrivateMessagesController < AdminController
  respond_to :json

  def create
    private_message = PrivateMessage.new(params[:private_message])
    private_message.save
    respond_with private_message
  end
end

view

<%= form_for @private_message, :remote => true, :html => {"data-type" => "json"}  do |f|
  f.input :body
 ... 
  end %>

js/coffeescript

i just add all error to a string and show them..

$("#new_private_message").on 'ajax:error', (event, data, status) ->
  error = "Errors: "
  $.each $.parseJSON(data.responseText), (field, errorMessage) ->
    error += "#{field}-#{errorMessage} "
  $('#errors').html(error)

json error object

{"body":["Please enter a message."],"subject":["Please enter a message."]}

my questions!

  • do i have to parse the json myself?
  • how can i add the error message to the field?
  • Should it not be part of standard jquery-ujs?
aka47
  • 41
  • 4

1 Answers1

2

do i have to parse the json myself?

Yes, error responses are not parsed by the jQuery Ajax API automatically. You must do this yourself.

how can i add the error message to the field?

Here is a very quick example of how to handle the errors: http://jsfiddle.net/hpM6W/

Though a much more exhaustive solution is required. For example in the sample I provided submit twice and see what happens...

There are many toolkits and libraries for rich client side validation and presentation of error messages. I would highly recommend looking at jQuery Validation Plugin to get started with form validation. You should still always do server side validation and return any errors.

What I've done in the past is a hybrid model where I would do client side validation as a convenience to the user (better user experience) as well as use the jQuery Validation Plugin to render the result of the server side validation via the showErrors method.

Here's a quick example: http://jsfiddle.net/GNq84/ on how to use showErrors to display the resulting error messages from server side validation. Note that with this example submitting multiple times works much better.

There is one caveat however, showErrors expects errors like so: { "element": "message" } and not what you current have which is: { "element": [ "message1", "message2" ] }, but I'll leave that up to you to solve :)

Community
  • 1
  • 1
Marc Gagne
  • 819
  • 5
  • 7