Archive

Archive for March, 2011

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);
  },
 });
});
Categories: Rails Tags: , , ,