Wiki Search

CS 352 Wiki Web Development 3

| edit page | page history | Sign in |

Day 17 Wiki Notes main content

Notes Index

Prototype Ajax Library

As previously mentioned, one popular library of Ajax JavaScript methods used by PHP programmers is Prototype written by Sam Stephenson.

There is no shortage of documentation and tutorials on Prototype.

Exercise 1 - Using Prototype

  1. Download the latest Prototype library and save it as prototype.js in your u:\htdocs folder
  2. Start up HTML-Kit, create a new XHTML document, and save it as u:\htdocs\Day17\Day17.html
  3. In the head section of the Day17.html document, place the following JavaScript code

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

In the body of the page add the following HTML code

<p id="para1">This is paragraph one</p>
<p id="para2">This is paragraph two</p>

<p><input id="testButton" type="button" value="Test 1" onclick="test1();"/></p>

Start up the Abyss Web Server view your Day17.html page in the browser

Event.observe method

Rather than intermixing the presentation view and the controller view, it is generally preferred to keep these two layers separate.

Prototype provides an easy way to register event handlers with events using the Event.observe method

// Once the window has loaded, call function init (same as &lt;body onload="init();"&gt;
Event.observe(window, 'load', init);

function init()
{
   Event.observe('testButton', 'click', test1);
   // register the other event handlers
}

Prototype Utility Methods

Prototype provides a number of utility methods. They are convenient in that they save typing.

Using the $ Prototype method

<script type="text/javascript">
function test1()
{
   var p = $("para1");

   alert(p.innerHTML);
   p.hide();   //or p.show();
   p.addClassName('hidden');
}
</script>

Test your Day17.html page in the browser.

The $ function can also accept a comma-delimited list of ids and it returns an array of element references.

Using the $F Prototype method

<fieldset>
<p><input id="f1" type="text" />
</p>
<textarea id="f2" rows="3" cols="15"></textarea>
<p><select   id="f3">
    <option>Item 1</option>
    <option>Item 2</option>
</select>
</p>
<p><input id="f4" type="checkbox" value="1" />One <input id="f5" type="checkbox" value="2" />Two<br />
</p>
<p><input id="testButton2" type="button" value="Test 2"/>
</p>
<p id="para3">
</p>
</fieldset>

function test2()
{
    var str = $F("f1") + '<br />' +
              $F("f2") + '<br />' +
              $F("f3") + '<br />' +
              $F("f4") + '<br />' +
              $F("f5");
    $("para3").innerHTML = str;
}

Add the event handler to the init method and test your Day17.html page in the browser.

Using Ajax.Request Asynchronous Calls with PHP

Prototype abstracts away many of the details of the XMLHttpRequest call to the server with the Ajax.Request method

XML data source

Imagine xyz company sales by employee are stored in the Day17.xml file

<?xml version="1.0" encoding="utf-8" ?>
<xyz>
  <sales>
     <employee-sales>
        <id>12</id>
        <year>2007-02</year>
        <sales>$12,222.36</sales>
      </employee-sales>
      <employee-sales>
        <id>13</id>
        <year>2007-02</year>
        <sales>$13,333.51</sales>
      </employee-sales>
      <employee-sales>
        <id>14</id>
        <year>2007-03</year>
        <sales>$14,444.51</sales>
      </employee-sales>
  </sales>
</xyz>

Generating Dynamic HTML Data

We could add a drop-down list to our web page for the user to select an employee name and see their sales data

<p><select id="Employees">
    <option value="12">Buchanan, Steven</option>
    <option value="13">Callahan, Laura</option>
    <option value="14">Davolio, Nancy</option>
  </select></p>
<p id="result"></p>

We could then add a JavaScript GetSalesById function to produce an Ajax request that gets the sales data and displays it in the result paragraph

function GetSalesById()
{
    var employeeId = $F('Employees');
    var url = 'Day17.php';

    var myAjax =
       new Ajax.Request(url, {method: 'get', parameters: {empID: employeeId}, onComplete: showResponse});
}

function showResponse(r)
{
    $('result').innerHTML = r.responseText;
}

We need register the change event for the Employees select element.

Finally, we need register the change eventto add the Day17.php page to actually read in the Day17.xml file and return the requested employee's sales data

<?php
   $empId = $_GET['empID'];

   $xml = simplexml_load_file('Day17.xml');

   $sales = $xml->xpath("/xyz/sales/employee-sales[id='$empId']/sales");

   foreach($sales as $s)
      echo  $s;
?>

Ajax.Updater

In the previous example, since all we did with the response text was to update a page element, we could substitute the Ajax.Request class with Ajax.Updater and dispense with the callback method showResponse

  var myAjax = new Ajax.Updater('result', url, {method: 'get', parameters: {empID: employeeId}});

Ajax.PeriodicalUpdater Class

The Ajax.PeriodicalUpdater class can be used to repeatedly create an Ajax.Updater instance, updating an element automatically after a certain time interval has elapsed.

For example, we could create a stock market ticker that updates every three seconds with

  var myAjax = new Ajax.PeriodicalUpdater('price', 'rand.php', {method: 'post', frequency: 3.0, decay: 1});

A simple PHP page to create a dummy stock market price is

 <?php
 $price = 50 + rand(0,5000)/100;
 echo "$price";
 ?>

DHTML based on Prototype

Many others have build JavaScript libraries that use Prototype to create DHTML effects on your Web pages.

| Return to top | | Site Management | Find Broken Links | edit | attr | Documentation Index | PmWiki.org |

Page last modified on April 23, 2008, at 02:24 PM