- Create a new Rails project named AjaxTime.
- Generate a controller with the name AjaxTime having the view page1.
- Add this source code to page1.html.erb:
<h1>AjaxTime Example</h1>
<p><span id="update">Hover here to display the current time.</span></p>
<p id="time"></p>
- Create a new partial at AjaxTime/app/views/time/_retrieve.html.erb with this source code:
<p><%= Time.now.strftime("%l:%M:%S%P, %A, %B %e, %Y") %></p>
- Add this method to the controller at AjaxTime/app/controllers/time_controller.rb:
def retrieve
render partial: 'retrieve', layout: false
end
-
Add this route to the the routes file: AjaxTime/config/routes.rb.
get 'time/retrieve'
- Add this jQuery code to AjaxTime/app/assets/javascripts/application.js:
$('document').ready(function( ) {
$("#update").mouseenter(function( ) {
$.get('/time/retrieve',
function(data) {
$("#time").html(data);
$("#update").css("background-color", "yellow");
});
});
$("#update").mouseleave(function( ) {
$("#time").html("");
$("#update").css("background-color", "white");
});
});
- Localhost URL to view page1:
http://localhost:3000/time/page1