Rails has a Prototype JavaScript library built in which contains all kind of Ajax and DOM manipulation javascript-objects and a Ruby module (JavascriptHelper) that wraps access to this JavaScript library.
To call functions from the Javascript Helper you have to include the prototype.js (it must be in the application's public/javascripts folder) in the <head> section of your rhtml page like this:
Now, to make a basic Ajax call from your rhtml page, you use link_to_remote method which takes 3 parameters: The text of the link, the Id of the HTML element to update and the Url of the action to call.
Or you can create a print_hello.rhtml view that contains:
AND a print_hello action:
That's all! You have had your first Ajax cup with RubyOnRails. Try it.
Here is the complet code:
To call functions from the Javascript Helper you have to include the prototype.js (it must be in the application's public/javascripts folder) in the <head> section of your rhtml page like this:
<%= javascript_include_tag "prototype" %>Now, to make a basic Ajax call from your rhtml page, you use link_to_remote method which takes 3 parameters: The text of the link, the Id of the HTML element to update and the Url of the action to call.
<%= link_to_remote(
"Say Hello Word",
:update => 'main',
:url => { :action => :print_hello }) %>
<div id="main">This is some text...</div>class DemoController < ApplicationController
def print_hello
render_text "<strong>Hello Word from Ajax!</strong>"
end
endOr you can create a print_hello.rhtml view that contains:
<strong>Hello Word from Ajax!</strong>AND a print_hello action:
class DemoController < ApplicationController
def print_hello
render(:layout => false)
end
endThat's all! You have had your first Ajax cup with RubyOnRails. Try it.
Here is the complet code:
The Controller: demo_controller.rb
class DemoController < ApplicationController
def index
end
def print_hello
end
end
-----------------------------------------------
The index.rhtml:
<html>
<head>
<title>My First Ajax cup with Rails</title>
<%= javascript_include_tag "prototype" %>
</head>
<body>
<%= link_to_remote(
"Say Hello Word",
:update => 'main',
:url => { :action => :print_hello }) %>
<div id="main">This is some text...</div>
</body>
-------------------------------------------
The print_hello.rhtml:
<strong>Hello Word from Ajax!</strong>