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

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:

  1. <%= form_for(@upload, :html =>{:multipart => true}, :remote => 'true') do |f| %>
  2.   <% if @upload.errors.any? %>
  3.     <div id="error_explanation">
  4.       <h2><%= pluralize(@upload.errors.count, "error") %> prohibited this image from being saved:</h2>
  5.       <% @upload.errors.keys.each do |field| %>
  6.         <% @upload.errors[field].each do |msg| %>
  7.           <% if field.to_s == "uploads.upload_content_type" %>
  8.             <li><%= field.to_s + " " + msg %></li>
  9.         <% end %>
  10.       <% end %>
  11.     </div>
  12.   <% end %>
  13.   <div>
  14.     <p>
  15.       <%= f.file_field :upload %>
  16.     </p>
  17.   </div>
  18.   <div class="actions">
  19.     <%= f.submit :class => 'button' %>
  20.   </div>
  21.   <%= f.hidden_field :product_id, :value => @upload.product_id %>
  22. <% end %>

Form JavaScript:

  1. /* Wait for document to load */
  2. $(document).ready(function() {
  3.     create_ajax_form('new_upload');
  4. })
  5.  
  6. /* Create an ajax form */
  7. function create_ajax_form(form_id){
  8.  
  9.    //Handle ajax submission
  10.    $j('#' + form_id).submit(function(){
  11.  
  12.        //Send for data
  13.        $j.post($j(this).attr("action"), $j(this).serialize(), null, "script");
  14.  
  15.        //Return false
  16.        return false;
  17.    });
  18. }

Controller Action:

  1. #Create an upload
  2.   def create
  3.  
  4.     #Create vars
  5.     @upload = Upload.new(params[:upload])
  6.  
  7.     #Create responses
  8.     respond_to do |format|
  9.       if @upload.save
  10.  
  11.         #Retrieve product
  12.         @product = Product.find_by_id(@upload.product_id)
  13.  
  14.         #Create success responses
  15.         format.html { redirect_to @product, :notice => 'Image Added Successfully!'}
  16.         format.js
  17.       else
  18.  
  19.         #Create error responses
  20.         format.html { render :action => 'new'}
  21.         format.js
  22.       end
  23.     end
  24.   end

JavaScript Response:

  1. alert('test');

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.