On 8/9/06, Jim W. [email protected] wrote:
<% for photo in @pic -%>
Can AJAX receive resultsets from ROR?
Firstly, AJAX is not a thing that is “somewhere in Rails”. AJAX is a
name for a bunch of related technologies that can be used to perform
http requests in the background, without reloading the full page. In
Rails, an Ajax call gets mapped to a controller method just like any
other request. You can use the output from the method (normally a
rendered partial) to update a named html element in your view.
To answer your question:
yes, this is entirely possible using Ajax, but if all you need to do
is to change an image, you would probably be better off doing it with
just javascript (Ajax-based solution further down):
Using Javascript:
-
large image:
![]()
-
thumbnail bar in your view:
<% for thumbnail in @thumbnails %>
<img src="<%= thumbnail.url %>" onclick=’$(‘big_image’).src=’<%=
thumbnail.image_url %>’"
<% end %>
Assuming that the thumbnail class has fields for url (of the
thumbnail) and image_url (of the large image).
BTW, the $(‘big_image’) notation uses the Prototype “$” function,
which is shorthand for document.getElementById. You need to <%=
include_javascript_tag :defaults %> somewhere for this to work.
Using Ajax:
If, for displaying a large image you also want to display other
information (say a description of the image), you can use ajax calls
like so:
- in your controller:
def large_image
image_id = params[:id]
img = Image.find(image_id)
render :partial=>“image”, :locals=>{:image=>image}
end
- in you partial (called _image.rhtml):
![]()
<%= image.description %>
- In your main view:
<%= render :partial=>'image', :locals=>{:image=>product.images[0]} %>
<% for thumbnail in @thumbnails %>
<img src="<%= thumbnail.url %>" onclick=‘remote_function
:update=>‘big_image’, :url=>{:action=>large_image,
:id=>thumbnail.image_id}’"
<% end %>
As you can see, for simply showing a different image, the pure
javascript version is much less verbose, which is a good sign that
it’s the better solution.
Max