Base on 'Agile Web Development with Rails, Third Edition', I created a cart with Ajax, but Ajax isn't working for me. My code is as follows:
/store/index.html.erb:
<%= form_tag({:action=>'add_to_cart', :id=>product}, :remote=>true ) do %>
<%= submit_tag "Add to Cart" %>
<% end %>
/layouts/store.html.erb:
<head>
...
<%= javascript_include_tag :defults %>
...
</head>
/controllers/store_controller.rb:
def add_to_cart
...
respond_to do |format|
format.js
end
...
end
add_to_cart.js.rjs
page.replace_html("cart",:partial => "cart", :object=>@cart)
Rails 3.1, Ruby 1.9.3.
RJS isn't a part of Rails any more. You can use jQuery instead without any additional download required: just don't use the .rjs
at the end. If you know CoffeeScript, it's also available here: name your file *.coffee
and you are done. Also you can name it *.coffee.erb
to allow the ERb to preprocess you file but this feature is allowed by default even for simple *.coffee
-files.
UPD:
page.replace_html("cart",:partial => "cart", :object=>@cart)
Should become:
$("#cart").html("<%= j render(@cart) %>")
js templates are named as name.js.erb in Rails 3.
Let me assume you are going to replace "cart" div in ajax call and you have jQuery. create add_to_cart.js.erb with the following code.
$("#cart").replaceWith('<%=escape_javascript(render :partial => 'cart', :object=>@cart) %>');