Rails 3 : Upload image file using AJAX form submission

I am trying to upload an image in RAILS 3 using AJAX form submission ,
this
is my code :

<%= form_for(:image, :remote => true, :url => {:controller=>
‘questions’,:action => ‘upload’}, :html => {:id=>‘qimage_upload’}) do
|f| %>

<%= f.file_field :image, :onchange => 

“$(this).parents(‘form’).submit();” %>

<% end %>

I have set the :remote => true option above and submitting the form with
an
onchange event . I have the following code in controller :

def upload

 if request.xhr?
    @image = Image.new(params[:image])
    @image.save

        respond_to do |format|
            format.js { render :layout=>false }
       end
 else
       render :text => 'Request Wasnt AJAX'
 endend

If I change the field to text in the form , the request is
AJAX(everything
else remaining same) but with an image field the request is always AJAX
. I
have included ‘jquery’ and ‘jquery_ujs’ in my application.js file as
well.

My action renders the text everytime , the request does not seem to be
AJAX
style despite the remote tag being set (it appears correctly even in the
final HTML). I can’t figure out where I am going wrong with this . I
have
tested it in the latest browser version of FF and Chrome , so I don’t
think
it’s a browser issue. Any ideas ?

On Wednesday, May 8, 2013 10:40:32 AM UTC+1, Varun Jain wrote:

I am trying to upload an image in RAILS 3 using AJAX form submission ,
this is my code :

You can’t upload files over ajax (at least not without using the HTML5
File apis, which you may not be able to rely on). The usual trick is to
do
the upload in a hidden iframe so that it doesn’t block the ‘main’ page.

Fred