Saturday, November 6, 2010

Using ajax call with file field!

Sometime ago I had real trouble using file field and ajax call together. I wanted to browse a file and display the contents in the same page. Then after some research I came across gem called "remotipart". This gem is really helpful.

To use this gem follow these simple steps
1. Include "gem remotipart" in your Gemfile
2. Bundle install
3. type this in your console: rails generate remotipart
4. Include jquery-1.4.2-min.js, rails.js, jquery.form.js and jquery.remotipart.js as your javascript files
5. Suppose you are using this in you new.html.erb file, then do this
<%= form_for @product, :html => { :multipart => true }, :remote => true do |f| %>
<%= f.label :file_upload %>
<%= f.file_field :file_upload %>
<%= f.submit %>
<% end %>
6. In your create controller include: format.js {} instead of format.html{}
7. In create.js.erb file :
<%= remotipart_response do %>
//Write your javascript code here.
<% end %>

If you have any confusions go to https://github.com/formasfunction/remotipart. This site really helped me a lot.

7 comments:

  1. Glad you found my Remotipart gem useful and good luck learning Rails.

    ReplyDelete
  2. I can't seem to get it to work. I have rails 3 and followed the fixes and tried to build a test app based on the tutorial. It stalls out with the Completed 406 Not Acceptable. I would really like to use it but can't waste any more time debugging :(

    ReplyDelete
  3. @formasfunction: Thank you for the gem.. it has really helped us.
    @rprambo: May be there is some error in your js file... also you need to include remotipart.js and jform.js in your file. I hope you did it!

    ReplyDelete