1

I am using AJAX to upload an image (with carrierwave gem) and want to display the image after uploading without refreshing or redirecting the page. Currently, after I upload an image it redirects to /images rather than staying on the / home page.

image_controller.rb:

def create
  @image = Image.new(params[:image])
  respond_to do |format|
    if @image.save
     format.js
    end
  end
end

_upload.html.erb:

<%= form_for @image, :html => { :multipart => true }, :remote => true do |f|%>
  <p>
  <%= f.file_field :image %>
  </p>
  <p><%= f.submit "Upload image", :class => 'btn primary', :id => 'image-upload' %></p>
<% end %>  

create.js.erb:

$('images-show').replaceWith('<%=j render 'shared/show_image' %>');

How do I prevent the redirect to /images after an image upload?

ramz15
  • 2,351
  • 3
  • 18
  • 22
  • I don't know the answer to your problem but a little friendly advice. Always use escape_javascript when rendering a partial to avoid malicious code. See http://stackoverflow.com/questions/1620113/why-escape-javascript-before-rendering-a-partial for more info. So it should be `$('images-show').html('<%=escape_javascript(render 'shared/show_image') %>');` – Ashitaka Jan 31 '12 at 10:53
  • Thanks for the advice! Didn't know exactly what escape_javascript does. I read in the API docs that j can be used in place of escape_javascipt, is this true? – ramz15 Jan 31 '12 at 11:56
  • it is doing a POST request. How do I tell it to do a GET request? – ramz15 Jan 31 '12 at 17:15

1 Answers1

1

For starters, make sure you have gem 'jquery-rails' in your Gemfile. Then make sure that you have <%= javascript_include_tag "application" %> in the head of your html document application.html.erb and that the file you are including, application.js has the lines:

//= require jquery
//= require jquery_ujs
Ashitaka
  • 19,028
  • 6
  • 54
  • 69