Rails 4 - Error Handling Through Ajax - Error Failing

I am trying to submit a "blank" form to cause an error.

However, it still responds with the Success function and does not throw an error. But records are not added.

The form works fine when I submit it with information in the input field.

the form:

<%= simple_form_for :course, :url => {:action => 'create'}, :remote => true do |f| %> <%= f.input :title %> <%= f.submit "Submit" %> <% end %> 

Model:

 class Course < ActiveRecord::Base validates :title, presence: true end 

Controller:

  def create @course = Course.new(course_params) respond_to do |format| if @course.save format.html { redirect_to(:controller => 'schedule', :action => 'index') } format.js else format.html { render :action => "new" } format.js end end end 

create.js.erb

 $(document).ready(function() { $("form").on("ajax:success", function(e, data, status, xhr) { alert("Success!"); }).bind("ajax:error", function(e, xhr, status, error) { alert("Error!"); }); }); 

general / error _messages.html.erb

  <% if object && object.errors.size > 0 %> <div id="errorExplanation"> <h2><%= pluralize(object.errors.size, "error") %> prohibited this record from being saved.</h2> <p>There were problems with the following fields:</p> <ul> <% object.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> 

Any ideas on what I'm doing wrong here? Thanks!

+6
source share
2 answers

You do not need to have document.ready in your js.erb file. You could do something like this

controller

 if @result = @course.save .. 

create.js.erb

 <% if @result %> alert("Success!"); <% else %> $('#error-div').html('<%= j(render :partial => 'shared/error_messages', :object => @course) %>'); <% end %> 
+8
source

Something you need to know:


Mistakes

Ajax errors occur only with AJAX errors (not Rails errors)

It took me a long time to figure this out - just because your Rails method is not executing does not mean that your Ajax call will throw an error. Ajax will succeed because it sent data to the server


Status

To call the Ajax Error function, you can use the status argument to send the error header:

rails reply_to format.js API

  respond_to do |format| if @course.save format.html { redirect_to(:controller => 'schedule', :action => 'index') } format.js else format.html { render :action => "new" } format.js { render status: :500 } end 
+8
source

All Articles