Task D: A Dash Of Ajax #0

Giuseppe:

Looking at APIs I tried the following code:

<%= link_to_remote(image_tag(product.image_url), :update => "cart", :url => { :action => :add_to_cart, :id => product }) %>

But it didn't work, any clue?


Well, thanks to my invaluable friend at http://www.redvex.it/ I catched the error.
The code should just link to the action in the store controller since there it will trigger the rjs template.
So I just deleted the

:update => "cart",

parameter to let the link_to_remote helper just call the action bound to the rjs template.
The correct snippet is:
<%= link_to_remote(image_tag(product.image_url), :url => { :action => :add_to_cart, :id => product }) %>

A great thanks to G.


Again, an update to the code.
Checking if the code worked as expected also with javascript disabled, I realized the link didn't work since it had just the onclick code and no href value (just the #). Consulting the APIs I fund the html_otion I was looking for to create the href value just in case javascript were disabled.
The updated code is:

<%= link_to_remote(image_tag(product.image_url),{:url => { :action => :add_to_cart, :id => product }}, :href => url_for(:action => :add_to_cart, :id => product)) %>

Where

:href => url_for(:action => :add_to_cart, :id => product))

does the magic.

Trientalis says:

I used the form_remote_tag as recommended:

<% form_remote_tag :url => { :action => :add_to_cart, :id => product } do %> 
    <%= image_submit_tag (product.image_url, :alt => product.title, :title => "Add to cart", :id => "product_picture") -%>
<% end %>

This works with and without javascript. The id product_picture is used to style the picture, because it will loose its float etc. otherwise. The css-entry looks as follows:

#product_picture {
  width: 75px;
  float: left;
  text-decoration: none;
}

Chris says:

You should give the image_submit_tag a :class instead of an :id, because there will be more than one of them on a page. IDs should be reserved for single objects, while classes should be used when there will be more than one type of that object on a single page, for validation reasons.

Code change is very minor:

<% form_remote_tag :url => { :action => :add_to_cart, :id => product } do %> 
    <%= image_submit_tag (product.image_url, :alt => product.title, :title => "Add to cart", :class => "product_picture") -%>
<% end %>
.product_picture {
  width: 75px;
  float: left;
  text-decoration: none;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License