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. My problem was solved with this gem.
To use this gem follow these simple steps
- Include gem remotipart in your Gemfile
- Run bundle install from your terminal
- Generate remotipart for rails by running following from your terminal
rails generate remotipart
- Include jquery-1.4.2-min.js, rails.js, jquery.form.js and jquery.remotipart.js as your javascript files
- Suppose you are using this in your new.html.erb file, the form should look like the form below
<%= form_for @product, :html => { :multipart => true }, :remote => true do |f| %>
<%= f.label :file_upload %>
<%= f.file_field :file_upload %>
<%= f.submit %>
<% end %>
- In your create controller include: format.js {} instead of format.html{}
- In create.js.erb file :
<%= remotipart_response do %>
//Write your javascript code here.
<% end %>
I hope this post helped you.