Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - Error Handling via Ajax - Error not firing

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

However, it is still responding with the "Success" function and not flagging an error. But, no records are being added.

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

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!");
  });
 });

shared/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 am doing wrong here? Thanks!

like image 873
Dodinas Avatar asked Jan 17 '14 17:01

Dodinas


2 Answers

You dont 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 %>
like image 78
Santhosh Avatar answered Nov 09 '22 22:11

Santhosh


Something you need to know:


Errors

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

It took me a long time to figure this out -- just because your Rails method doesn't succeed, doesn't mean your Ajax call will trigger an error. Ajax will succeed because it's sent the data to the server


Status

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

rails respond_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  
like image 8
Richard Peck Avatar answered Nov 09 '22 21:11

Richard Peck