Home > Rails > Rails and AJAX Image Upload using jQuery

Rails and AJAX Image Upload using jQuery

Hi,

When uploading image in normal method,  getting result after page reload. Its quit not looking good. So tried simple method using jquery,

image upload action look like below in controller

 @image = Image.new(params[:user_avatar])
 @image.save
and
the view page look like,
<% remote_form_for(:user_avatar, :url => { :controller => "users", :action => :avatar_upload }, :html => { :method => :post, :id => 'uploadForm', :multipart => true }) do |f| %>
Upload a file: <%= file_field_tag "user_avatar", :size => 15 %><%= submit_tag 'Upload' %>
<% end %>

and important below script,

$('#uploadForm input').change(function(){
 $(this).parent().ajaxSubmit({
  beforeSubmit: function(a,f,o) {
   o.dataType = 'json';
  },
  complete: function(XMLHttpRequest, textStatus) {
   // For example, if you have an image elemtn with id "user_avatar", then
    
$('#user_avatar').attr('src', XMLHttpRequest.responseText);
  },
 });
});
Advertisements
Categories: Rails Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: