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:

{:multipart => true}, :remote => 'true') do |f| %>
  
    

prohibited this image from being saved:

  • 'button' %>
    @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');
    

    Posted

    in

    , , ,

    by

    Comments

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out /  Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out /  Change )

    Connecting to %s

    Create a website or blog at WordPress.com

    %d bloggers like this: