Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the Ruby on Rails CarrierWave gem work with Ajax?

For some reason using the CarrierWave gem with Ajax doesn't seem to be working for me. Am I doing something wrong? I followed the 253 CarrierWave Railscast well and it works without AJAX but in my application I need to use AJAX. Here is my code:

The params list after selecting a jpeg in the image file field:

Parameters: {"item"=>{"remote_image_url"=>""}}

new.html.erb:

<%= form_for(@item, :url => create_item_path, :html => {:id => "create_item_form", :multipart => true}) do |f| %>
    <p>
      <%= f.file_field :image %>
    </p>
    <p>
      <%= f.label :remote_image_url, "or image URL" %><br />
      <%= f.text_field :remote_image_url %>
    </p>
    <%= f.submit "Save", :id => "save_button" %>
<% end %>

application.js

$("#create_item_form").submit(function() {
    $.ajax({
      type: "POST",
      url: $(this).attr("action"),
      dataType: "script",
      data:  $("#destination_item").sortable('serialize') + "&" + $(this).serialize()
      });
      return false;
});

item.rb

class Item < ActiveRecord::Base
  attr_accessible :description, :image, :remote_image_url
  belongs_to :user
  has_many :item_sub
  mount_uploader :image, ImageUploader
end

schema.rb

  create_table "item", :force => true do |t|
    t.integer  "user_id"
    t.string   "title"
    t.string   "image"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

I have the carrierwave gem in my gemfile and I haven't changed anything in the app/uploaders/image_uploader.rb.

Thanks for all your help!

like image 832
EverTheLearner Avatar asked Feb 25 '12 06:02

EverTheLearner


2 Answers

You can now upload files through ajax without the use of external libraries by using FormData()

SEE: LINK 1 & LINK 2

like image 153
Darcbar Avatar answered Nov 15 '22 15:11

Darcbar


There is nothing that can be done without a using a library like Uploadify. This is because the XMLHttpRequest (AJAX) standard has no support for file uploads. The only way you can really fake this is using an iFrame with Flash. Uploadify is the best of these options, and it has the best documentation. This is what has to be done on the client side (browser). Uploadify really isn't a ruby gem, its a collection of flash and js to allow the browser to 'fake it'.

On the server side, you can use carrierwave to support the uploads, but you need a way to get them there from the client side. Here is an extremely similar question which should give you the instructions that you need.

Rails Carrier Wave with JQuery Uploader

Hope this helps,

Joe

like image 34
TheDelChop Avatar answered Nov 15 '22 16:11

TheDelChop