To Examples

AjaxTime Example

Directions

  1. Create a new Rails project named AjaxTime.
  2. Generate a controller with the name AjaxTime having the view page1.
  3. 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>
    
  4. 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>
    
  5. Add this method to the controller at AjaxTime/app/controllers/time_controller.rb:
     def retrieve
      render partial: 'retrieve', layout: false
    end
    
  6. Add this route to the the routes file: AjaxTime/config/routes.rb.
    get 'time/retrieve'
    
  7. 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");
      });
    }); 
    
  8. Localhost URL to view page1:
    http://localhost:3000/time/page1