Ajax on Rails 26-Jul-16

advertisement
Ajax on Rails
26-Jul-16
Ajax in .rhtml


In the <head> section of your .rhtml page, do:
<%= javascript_include_tag "prototype" %>
The above code adds several files to your .rhtml page


Included is JavascriptHelper, which lets you write Ruby
code in place of Javascript code
Here’s a simple .rhtml page:

<%= link_to_remote("Do the Ajax thing",
:update => 'mydiv',
:url => { :action => :say_hello }) %>
<div id="mydiv">This text will be changed</div>
Ajax on the server side

The code on the preceding slide will call a method
named say_hello when the link is clicked, so here it is:


def say_hello
render(:layout => false)
end
We also need a corresponding say_hello.rhtml file:

<em>Hello from Ajax!</em> (Session id is
<%= session.session_id %>)
Results

Before clicking the link:
Do the Ajax thing
This text will be changed
 After clicking the link:
Do the Ajax thing
Hello from Ajax! (Session ID is d633a8cd4416dfc7253)
The End
Example from: Agile Web Development with Rails
by Dave Thomas and David Heinemeier Hansson
Download