Dave
Dave

Reputation: 19320

How do I return validation errors in JSON form from a form that submits remotely?

I’m using Rails 4.2.3 and the “:remote => true” property to submit a form remotely. However, I’m having trouble displaying the validation errors coming back. In my controller I have

  def create
    @my_object = MyObject.new(my_object_params)
    @current_user = User.find(session["user_id"])
    @my_object.user = @current_user
    @date = Date.strptime(my_object_params[:day], "%m/%d/%Y")
    @my_object.day = @date
    respond_to do |format|
      if @my_object.save
        flash[:notice] = 'Saved successfully'
        format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }
        format.js { render js: "window.location='/users'" }
      else
        format.html { render action: "index" }
        format.json { render json: @my_object.errors, status: :unprocessable_entity }
        format.js { render json: { error: @my_object.errors, success: false }, content_type: 'application/json' }
      end
    end
  end

And in my coffee script, I have

$(document).ready (data) ->
  $("#add_form").bind "ajax:error", (xhr, status, error) ->
    console.log(xhr) 
    console.log(status)
    console.log(error)
    render_form_errors(xhr, error)
    #Give an alert message
  $("#add_form").bind "ajax:before", (evt, data, status, xhr) ->
    hrs = $('#my_object_hour').val();
    min = $('#my_object_minute').val();
    sec = $('#my_object_second').val();
    $('#my_object_my_object_times_attributes_0_time_in_ms').val((hrs * 60 * 60 + min * 60 + sec) * 1000);

But none of the three fields, “xhr, status, error” contains the JSON errors. The output of the console.log statements is

j…y.Event {type: "ajax:error", timeStamp: 1465418664628, jQuery112103593207809583596: true, isTrigger: 3, namespace: ""…}
users.self-a27ba2c….js?body=1:13 Object {readyState: 4, responseText: "ArgumentError in MyObjectsController#create↵↵invalid d…VER_PROTOCOL: "HTTP/1.1"↵↵Response headers↵None↵↵", status: 500, statusText: "Internal Server Error"}
users.self-a27ba2c….js?body=1:14 error

How do I transmit these back from my controller?

Thanks, -

Edit: In response to the answer, I edited my controller in the manner specified, and added this to my coffee script ...

$(document).ready (data) ->
  $("#add_form").bind "ajax:failure", (e, xhr, status, error) -> 
    console.log('error');
    console.log(e);
    console.log(xhr);
    console.log(status);
    console.log(error);
    render_form_errors(xhr, error)  
  $("#add_form").bind "ajax:error", (xhr, status, error) ->
    console.log(xhr)
    console.log(status)
    console.log(error)
    render_form_errors(xhr, error) 
    #Give an alert message
  $("#add_form").bind "ajax:before", (evt, data, status, xhr) ->
    hrs = $('#my_object_hour').val();
    min = $('#my_object_minute').val();
    sec = $('#my_object_second').val();
    hrs_in_ms = hrs * 60 * 60 * 1000
    min_in_ms = min * 60 * 1000
    sec_in_ms = sec * 1000
    ms = hrs_in_ms + min_in_ms + sec_in_ms
    alert(ms)
    $('#my_object_my_object_times_attributes_0_time_in_ms').val(ms);

but upon submitting my form with errors, the none of the above gets called. I know there are errors because I see (through debugging) the "else" clause of the "if @my_object.save" being called.

Upvotes: 0

Views: 994

Answers (1)

Saad
Saad

Reputation: 1902

First of all you will need to fix that 500 error, I have not taken your example but this is a rough example.

bugs.js

$(document).ready(function() {
  console.log('hiii');
  $('#new_bug')

  .on('ajax:success', function(e, data, status, xhr) {
    console.log('success');
    console.log(e);
    console.log(data);
    console.log(status);
    console.log(xhr);
  })

  .on('ajax:error', function(e, xhr, status, error) {
    console.log('error');
    console.log(e);
    console.log(xhr);
    console.log(status);
    console.log(error);
  })
})

in your controller, for e.g. my controller is bugs_controller.js

  def create
    @bug = Bug.new(bug_params)

    respond_to do |format|
      if @bug.save
        format.html { redirect_to @bug, notice: 'Bug was successfully created.' }
        format.json { render :show, status: :created, location: @bug }
        format.js { render json: { success: true, bug: @bug.to_json }, content_type: 'application/json' }
      else
        format.html { render :new }
        format.json { render json: @bug.errors, status: :unprocessable_entity }
        format.js { render json: { error: @bug.errors, success: false }, content_type: 'application/json' }
      end
    end
  end

If you want ajax:error callback for your else block, you will need to provide with a different status code like 400, 500. For e.g. format.js { render json: { error: @bug.errors, success: false }, content_type: 'application/json', status: 500 }, although I wouldn't really recommend this, as this is not the right way to do it. Your ajax:success will take care of validation errors, also since we are passing success: false we can check if there are validation errors in js.

Upvotes: 1

Related Questions