Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Josue Negron
Josue Negron
4,193 Points

How to get error detail on ajax POST?

How can I get the detail of an error in a POST? For example I have the following validation: validates :name, presence: true If the user leaves the field in blank, I want to warn the user about the mistake: (1) view

<!-- NOTIFICATION AREA -->
        <div class="alert alert-info alert-dismissible" id="alert_success_product" role="alert" style="display: none">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>          
        </div>
        <div class="alert alert-danger alert-dismissible" id="alert_error_product" role="alert" style="display: none">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>          
        </div>

(2) controller

  def add_product
    name = params[:name]
    price = params[:price]

    new_product = Product.new(name: name, price: price)

    if new_product.save      
      respond_to do |format|
        format.html {redirect_to root_path}
        format.json        
      end      
    else
      error = new_product.error.full_messages
      render :json => { :error => error }
    end
  end

(3) js

$(document).on("click", '#add_product', function() {    
  product_name  = $("#product_name").val()
  product_price = $("#product_price").val()

    $.ajax({
      url:      "/warehouses/add_product",
      type:     "POST",      
      datatype: "JSON",
      data:     {name: product_name, price: product_price},      
      success:  function() {              
              $("#alert_success_product").css('display', 'block');
              $("#alert_success_product").append( "<p> Success! </p>" ); //Display success message here
      },
      error: function(data) {                          
              $("#alert_error_product").css('display', 'block');
              $("#alert_error_product").append( data.error );  //Display error message here
      }
  });  
});

That is what I have so far, but it seems I'm missing something because data.error is not returning a value. Thanks in advance!