This AJAX example pulls the customer details for the selected customer and shows the results without refreshing the page. Please select one of the customers:

$customerSelect

 

The Prototype JavaScript library is used in this example. Please also see the Introduction to Ajax for a good tutorial.

This HTML page contains a customer Select control and a <div id='customerDetails'/> element:

<table cellspacing="8" cellpadding="8">
   <tr>
      <td> <select name="customerSelect">...</select> </td>
      <td> <div id="customerDetails"/> </td>
   </tr>
</table>

When you click on the select, an HTTP request (e.g. GET ajax-select.htm?pageAction=onChangeCustomer&customerId=202) is made to the page to get the customers details. These details are returned as HTML with a content-type of 'text/html':

<table border="0" cellspacing="2" cellpadding="2">
  <tr>
    <td><b>Name</b></td>
    <td>Alison Smart</td>
  </tr>
  ...
</table>
Prototype's Ajax.Updater then updates the inner HTML of the page registered <div id='customerDetails'/> element with the HTML content returned from the server.

Below is the necessary JavaScript to perform the Ajax request.

As soon as the browser DOM is loaded, Prototype's observe function is used to register a "change" listener on the "customerSelect" control. When you select an option, the Ajax.Updater is invoked to retrieve the customer details and update the target "customerDetails" div:

<html>
...
<body>
...

  $jsImports

  <script type='text/javascript' src='prototype.js'></script>

  <script type='text/javascript'>
    // Wait until browser DOM is loaded
    document.observe("dom:loaded", function() {

      // Observe the selected element's "change" event, which triggers the given function.
      // Note that $selector is a Velocity variable passed in from the AjaxSelect.java Page
      $('customerSelect').observe('change', function(event){

        // Retrieve the source of the event, in this case the Select control
        var select = Event.element(event);

        // Ajax.Updater requests the customer for the given customerId parameter
        // and replaces the inner HTML of customerDetails div
        new Ajax.Updater('customerDetails', '/click-examples/ajax/select/ajax-select.htm', {
          method: 'get',
          parameters: {'pageAction' : 'onChangeCustomer', 'customerId' : select.value}
        });
      });
    });
  </script>
</body>
</html>
The initialization code above is contained in the ajax-select.js template.