Simple Ajax Example

Here's a simple example that would appear in a Rails view:

  <h1>Time Ajax Demo</h1>
  <p><%= link_to 'Get Current Time', {action: 'refresh'}, 
         remote: true %>
  </p>
  <p id='currentTime'>
  Current time will appear here
  </p>

When the user clicks on the link, the browser makes an XMLHTTPRequest to the server, which will get routed to the refresh method in the controller (this uses the default routing rule in routes.rb).

The refresh method in the controller assigns @right_now the current time and then renders a js template (refresh.js.erb):

  document.getElementById("currentTime").innerHTML = "<%= @right_now %>";

The browser then executes this code, which selects the element with the id of currentTime and updates it with the value of @right_now.