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:

<%= form_for(@upload, :html =>{:multipart => true}, :remote => 'true') do |f| %>
  <% if @upload.errors.any? %>
    

<%= pluralize(@upload.errors.count, "error") %> prohibited this image from being saved:

<% @upload.errors.keys.each do |field| %> <% @upload.errors[field].each do |msg| %> <% if field.to_s == "uploads.upload_content_type" %>
  • <%= field.to_s + " " + msg %>
  • <% end %> <% end %>
    <% end %>

    <%= f.file_field :upload %>

    <%= f.submit :class => 'button' %>
    <%= f.hidden_field :product_id, :value => @upload.product_id %> <% end %>

    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');
    

    Leave a Reply