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

Form JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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:

1
alert('test');

Leave a Reply