POST http://192.168.1.3:3000 406 (Not Acceptable) - AJAX with Ruby on Rails

ErrorsjQueryRuby on RailsWeb Development

Just a quick post on an error I ran into today when trying to create an AJAX image upload with Ruby on Rails. When submitting an AJAX form I received the following error:

POST http://192.168.1.3:3000/uploads 406 (Not Acceptable)

It turns out that there is a fairly simple (and admittedly obvious) solution. Ensure that your controller has an appropriate response for JavaScript files:

i.e.
Form:

{:multipart => true}, :remote => 'true') do |f| %>
  
    <div id="error_explanation">
      <h2> prohibited this image from being saved:</h2>
      
        
          
            <li></li>
        
      
    </div>
  
  <div>
    <p>
      
    </p>
  </div>
  <div class="actions">
     'button' %>
  </div>
   @upload.product_id %>

Form JavaScript:

/* Wait for document to load */
$(document).ready(function() {
    create_ajax_form('new_upload');
})

/* Create an ajax form */
function create_ajax_form(form_id){

   //Handle ajax submission
   $j('#' + form_id).submit(function(){

       //Send for data
       $j.post($j(this).attr("action"), $j(this).serialize(), null, "script");

       //Return false
       return false;
   });
}

Controller Action:

#Create an upload
  def create

    #Create vars
    @upload = Upload.new(params[:upload])

    #Create responses
    respond_to do |format|
      if @upload.save

        #Retrieve product
        @product = Product.find_by_id(@upload.product_id)

        #Create success responses
        format.html { redirect_to @product, :notice => 'Image Added Successfully!'}
        format.js
      else

        #Create error responses
        format.html { render :action => 'new'}
        format.js
      end
    end
  end

JavaScript Response:

alert('test');