2
0
mirror of https://github.com/ACSPRI/queXS synced 2024-04-02 12:12:16 +00:00

Import from DCARF SVN

This commit is contained in:
azammitdcarf
2008-10-15 22:36:05 +00:00
parent 4f0b4f0bbb
commit 1445da495b
2237 changed files with 714445 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
Joshua Eichorn <josh@bluga.net> - Project Lead
David Coallier <davidc@php.net> - Project Lead
Laurent Yaish <laurenty@gmail.com> - Developer
Elizabeth Smith <auroraeosrose@gmail.com> - Developer
Arpad Ray <arpad@php.net> - Developer

View File

@@ -0,0 +1,7 @@
JPSpan serializer for compatibility
Additional functionality to helper class
Inline frame ajax fallback and file upload support
Something for Polling
Basic debugging tools (XMLHttpRequest tester, serialized items viewer, debug console)
Complete Documentation including basic tutorials and step by step for advanced uses
Framework integration - either documentation or some kind of API

View File

@@ -0,0 +1,3 @@
This is the README file, its loaded in lots of examples
See Index.php for details

View File

@@ -0,0 +1,49 @@
<?php
/**
* Example of Using HTML_AJAX_Action
*
* All the work happens in support/testHaa.class.php
* This class just attaches some acctions to calls to the server class
*
* This just shows basic functionality, what were doing isn't actually useful
* For an example on how one would actually use HTML_AJAX_Action check out the guestbook example
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2006 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
?>
<html>
<head>
<script type='text/javascript' src="auto_server.php?client=all"></script>
<script type='text/javascript' src="auto_server.php?stub=testHaa"></script>
<script type='text/javascript'>
// create our remote object so we can use it elsewhere
var remote = new testHaa({}); // pass in an empty hash so were in async mode
</script>
</head>
<body>
<h1>Basic HTML_AJAX_Action Usage</h1>
<ul>
<li><a href="#" onclick="remote.greenText('target')">Make Target Green</a></li>
<li><a href="#" onclick="remote.highlight('target')">Highlight Target</a></li>
<li><a href="#" onclick="remote.duplicate('target','dest')">Duplicate Target</a></li>
</ul>
<div id="target">
I'm some random text. Ain't I fun.
</div>
<div id="dest">
</div>
</body>
</html>

View File

@@ -0,0 +1,70 @@
<?php
/**
* Advanced usage of HTML_AJAX_Server
* Allows for a single server to manage exporting a large number of classes without high overhead per call
* Also gives a single place to handle setup tasks especially useful if session setup is required
*
* The server responds to ajax calls and also serves the js client libraries, so they can be used directly from the PEAR data dir
* 304 not modified headers are used when server client libraries so they will be cached on the browser reducing overhead
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// include the server class
include 'HTML/AJAX/Server.php';
// extend HTML_AJAX_Server creating our own custom one with init{ClassName} methods for each class it supports calls on
class TestServer extends HTML_AJAX_Server {
// this flag must be set to on init methods
var $initMethods = true;
// init method for the test class, includes needed files an registers it for ajax
function initTest() {
include 'support/test.class.php';
$this->registerClass(new test());
}
// init method for the livesearch class, includes needed files an registers it for ajax
function initLivesearch() {
include 'support/livesearch.class.php';
$this->registerClass(new livesearch());
}
// init method for the testHaa class, includes needed files an registers it for ajax, directly passes in methods to register to specify case in php4
function initTestHaa() {
include 'support/testHaa.class.php';
$this->registerClass(new testHaa(),'testHaa',array('updateClassName','greenText','highlight','duplicate'));
}
}
// create an instance of our test server
$server = new TestServer();
// init methods can also be added to the server by registering init objects, this is useful in cases where you want to dynamically add init methods
class initObject {
// init method for the test class, includes needed files an registers it for ajax
function initTest2() {
include 'support/test2.class.php';
$this->server->registerClass(new test2());
}
}
$init = new initObject();
$server->registerInitObject($init);
// you can use HTML_AJAX_Server to deliver your own custom javascript libs, when used with comma seperated client lists you can
// use just one javascript include for all your library files
// example url: auto_server.php?client=auto_server.php?client=Util,Main,Request,HttpClient,Dispatcher,Behavior,customLib
$server->registerJSLibrary('customLib','customLib.js','./support/');
// handle requests as needed
$server->handleRequest();
?>

View File

@@ -0,0 +1,31 @@
<?php
/**
* Test class used in other examples
* Constructors and private methods marked with _ are never exported in proxies to JavaScript
*
* @category HTML
* @package AJAX
* @author David Coallier <davidc@agoraproduction.com>
* @copyright 2005 David Coallier
* @license LGPL http://www.gnu.org/copyleft/lesser.txt
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
require_once 'HTML/AJAX.php';
class error_test
{
function error_test()
{
$ajax =& new HTML_AJAX;
$ajax->debugEnabled = true;
$ajax->debugSession = true;
set_error_handler(array(&$ajax, '_errorHandler'));
trigger_error("I don't know");
}
}
$t =& new error_test;
print_r($t);
?>

View File

@@ -0,0 +1,91 @@
<?php
/**
* AJAX form submission example
*
* @category HTML
* @package AJAX
* @author Arpad Ray <arpad@php.net>
* @author Laurent Yaish <laurenty@gmail.com>
* @copyright 2005 Arpad Ray
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
?>
<html>
<head>
<script type="text/javascript" src="server.php?client=all&stub=test"></script>
</head>
<body>
<pre id="target">
</pre>
<form action="server.php" method="post" onsubmit="return !HTML_AJAX.formSubmit(this, 'target', {className: 'test', methodName:'multiarg'});">
<table>
<tr>
<td>Text</td>
<td><input type="text" name="test_text" value="example" /></td>
</tr>
<tr>
<td>Single Select</td>
<td>
<select name="test_select">
<option value="example1">Example 1</option>
<option value="example2">Example 2</option>
</select>
</td>
</tr>
<tr>
<td>Multi Select</td>
<td>
<select name="test_select_multiple[]" multiple="multiple">
<option value="examplea">Example A</option>
<option value="exampleb">Example B</option>
<option value="examplec">Example C</option>
<option value="exampled">Example D</option>
</select>
</td>
</tr>
<tr>
<td>Single Checkbox</td>
<td><input type="checkbox" name="single_checkbox" value="single_check1" /></td>
</tr>
<tr>
<td>Multi Checkboxes</td>
<td>
<input type="checkbox" name="multi_checkbox[]" value="multi_check1" />1
<input type="checkbox" name="multi_checkbox[]" value="multi_check2" />2
<input type="checkbox" name="multi_checkbox[]" value="multi_check3" />3
</td>
</tr>
<tr>
<td>Radio Buttons</td>
<td>
<input type="radio" name="test_radio" value="radio_1" />1
<input type="radio" name="test_radio" value="radio_2" />2
<input type="radio" name="test_radio" value="radio_3" />3
</td>
</tr>
<tr>
<td>Textarea</td>
<td>
<textarea name="long_text">type a long string in here....</textarea>
</td>
</tr>
</table>
<input type="submit" name="submit" value="Submit form" />
</form>
<h3>JavaScript callback function target test</h3>
<form action="server.php" method="post" onsubmit="return !HTML_AJAX.formSubmit(this, function(result) { document.getElementById('target').innerHTML = result; }, {className: 'test', methodName:'multiarg'});">
<table>
<tr>
<td>Text</td>
<td><input type="text" name="test_text" value="example" /></td>
</tr>
</table>
</form>
</body>
</html>

View File

@@ -0,0 +1,45 @@
<?php
/**
* Simple grab example
*
* @category HTML
* @package AJAX
* @author Arpad Ray <arpad@php.net>
* @copyright 2005 Arpad Ray
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
include 'HTML/AJAX.php';
if (isset($_GET['grab'])) {
die('Grabbed from php!');
}
$ajax = new HTML_AJAX();
if ($ajax->handleRequest()) {
exit;
}
?><html>
<head>
<script type='text/javascript' src="../js/HTML_AJAX.js"></script>
<script type="text/javascript">
function grab()
{
var callback = function(result) {
document.getElementById('target').innerHTML = result;
}
HTML_AJAX.grab('grab.php?grab=1', callback);
}
</script>
</head>
<body>
<a href="javascript:grab()">grab</a>
<pre id="target">
</pre>
</body>
</html>

View File

@@ -0,0 +1,34 @@
<?php
/**
* Server that exposes a class for doing a fake guestbook
*
* @category HTML
* @package AJAX
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// include the server class
include 'HTML/AJAX/Server.php';
// extend HTML_AJAX_Server creating our own custom one with init{ClassName} methods for each class it supports calls on
class GuestbookServer extends HTML_AJAX_Server {
// this flag must be set to on init methods
var $initMethods = true;
// init method for the test class, includes needed files an registers it for ajax
function initGuestbook() {
include 'guestbook.class.php';
$this->registerClass(new Guestbook(),'guestbook',array('newEntry', 'clearGuestbook', 'deleteEntry', 'editEntry', 'updateSelect')); // specify methods so that we get case in php4
}
}
session_start();
// create an instance of our test server
$server = new GuestbookServer();
// handle requests as needed
$server->handleRequest();
?>

View File

@@ -0,0 +1,185 @@
<?php
/**
* Guestbook uses HTML_AJAX_Action class to interact with the page - the
* javascript is all written from here
*
* @category HTML
* @package AJAX
* @author Elizabeth Smith <auroraeosrose@gmail.com>
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
/**
* Require the action class
*/
require_once 'HTML/AJAX/Action.php';
class guestbook {
// constructor won't be exported
function guestbook() {
if (!isset($_SESSION['entries'])) {
$_SESSION['entries'] = array();
}
}
// data is an array of objects
function newEntry($data) {
//validation code is identical
$response = new HTML_AJAX_Action();
//remove any error nodes present
$response->removeNode('nameError');
$response->removeNode('emailError');
$response->removeNode('emailError2');
$response->removeNode('commentError');
//checking data
if(!isset($data['name']) or empty($data['name']))
{
//create error div after bad name node
$response->createNode('name', 'div', array('class' => 'error', 'innerHTML' => 'Name is a required field', 'id' => 'nameError'), 'insertAfter');
$error = TRUE;
}
if(!isset($data['email']) or empty($data['email']))
{
//create error div after bad name node
$response->createNode('email', 'div', array('class' => 'error', 'innerHTML' => 'Email is a required field', 'id' => 'emailError'), 'insertAfter');
$error = TRUE;
}
if($this->_checkEmail($data['email']) != TRUE)
{
//create error div after bad name node
$response->createNode('email', 'div', array('class' => 'error', 'innerHTML' => 'That email address is incorrect', 'id' => 'emailError2'), 'insertAfter');
$error = TRUE;
}
if(!isset($data['comments']) or empty($data['comments']))
{
//create error div after bad name node
$response->createNode('comments', 'div', array('class' => 'error', 'innerHTML' => 'Comment is a required field', 'id' => 'commentError'), 'insertAfter');
$error = TRUE;
}
if(!isset($error))
{
//clean name - strip tags and html_entity it :)
$data['name'] = htmlentities(strip_tags($data['name']));
//clean email - strip tags it
$data['email'] = strip_tags($data['email']);
//clean website - strip http://if needed
$data['website'] = strip_tags($data['website']);
if(strpos($data['website'], 'http://') === 0)
{
$data['website'] = str_replace('http://', '', $data['website']);
}
//clean like name
$data['comments'] = htmlentities(strip_tags($data['comments']));
//branch here depending on if form is new
if($data['submit'] == 'Edit Entry')
{
$old = $_SESSION['entries'][$data['key']];
//merge new data over old
foreach($data as $key => $value)
{
$old[$key] = $value;
}
$_SESSION['entries'][$data['key']] = $old;
//replace div innerHTML, fun fun
$response->assignAttr('entry'.$data['key'], 'innerHTML', $this->_makeDiv($data['key'], $_SESSION['entries'][$data['key']], TRUE));
//remove hidden input
$response->removeNode('key');
}
else
{
$data['date'] = date('j/n/Y, h:i');
$_SESSION['entries'][] = $data;
end($_SESSION['entries']);
$key = key($_SESSION['entries']);
$response->prependAttr('guestbookList', 'innerHTML', $this->_makeDiv($key, $data));
}
//reset the form
$response->assignAttr('name', 'value', '');
$response->assignAttr('email', 'value', '');
$response->assignAttr('website', 'value', '');
$response->assignAttr('comments', 'value', '');
$response->assignAttr('submit', 'value', 'Add Comments');
}
return $response;
}
// empty the guestbook
function clearGuestbook($data) {
$_SESSION['entries'] = array();
$response = new HTML_AJAX_Action();
$response->insertAlert('You will clear all entries, this cannot be undone!');
$response->assignAttr('guestbookList', 'innerHTML', '');
return $response;
}
// delete an entry from the guestbook
function deleteEntry($id) {
unset($_SESSION[$id]);
$response = new HTML_AJAX_Action();
$response->removeNode('entry'.$id);
return $response;
}
// puts a guestbook entry back in
function editEntry($id) {
$data = $_SESSION['entries'][$id];
$response = new HTML_AJAX_Action();
//send to the form
$response->assignAttr('name', 'value', $data['name']);
$response->assignAttr('email', 'value', $data['email']);
$response->assignAttr('website', 'value', $data['website']);
$response->assignAttr('comments', 'value', $data['comments']);
$response->assignAttr('submit', 'value', 'Edit Entry');
$response->createNode('submit', 'input', array('id' => 'key', 'name' => 'key', 'type' => 'hidden', 'value' => $id), 'insertBefore');
return $response;
}
function updateSelect($id)
{
$response = new HTML_AJAX_Action();
$attr = array('id' => $id, 'name' => $id);
$response->replaceNode($id, 'select', $attr);
for ($i=1;$i<=10;$i++)
{
$attr = array('value' => $i, 'innerHTML' => 'Option ' . $i);
$response->createNode($id, 'option', $attr, 'append');
}
return $response;
}
function _makeDiv($key, $data, $replace = FALSE) {
$div = '';
if($replace == FALSE)
{
$div .= '<div class="entry" id="entry'.$key.'">';
}
$div .= '<h3><a href="mailto:'.$data['email'].'">'.$data['name'].'</a></h3>';
if(!empty($data['website']))
{
$div .= '<a href="http://'.$data['website'].'">'.$data['website'].'</a><br />';
}
$div .= '<p>'.$data['comments'].'</p>'
.'<div class="small">Posted: '.$data['date'].' | '
.'<a href="#" onclick="editentry('.$key.');">Edit</a> | '
.'<a href="#" onclick="deleteentry('.$key.');">Delete</a></div>';
if($replace == FALSE)
{
$div .= '</div>';
}
return $div;
}
function _checkEmail($email)
{
//checks proper syntax
if(preg_match( '/^[A-Z0-9._-]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z.]{2,6}$/i' , $email))
{
return true;
}
return false;
}
}
?>

View File

@@ -0,0 +1,202 @@
<?php
/**
* A simple guestbook with the goal of not a line of javascript :)
*
* @category HTML
* @package AJAX
* @author Elizabeth Smith <auroraeosrose@gmail.com>
* @copyright 2005 Elizabeth Smith
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
//require the helper class - it will take care of everything else
require_once 'HTML/AJAX/Helper.php';
//since we're not REALLY using a backend like a database, use sessions to store data
session_start();
//set up HTML_AJAX_Helper
$ajaxHelper = new HTML_AJAX_Helper();
//tell it what url to use for the server
$ajaxHelper->serverUrl = 'auto_server.php';
//add haserializer to set
$ajaxHelper->jsLibraries[] = 'haserializer';
// Open tags problem... I know ugly.
$ajaxHelper->stubs[] = 'guestbook';
print '<?xml version="1.0" encoding="utf-8"?>';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>My Guestbook</title>
<?php
// output a javascript neded to setup HTML_AJAX
echo $ajaxHelper->setupAJAX();
?>
<script type="text/javascript">
HTML_AJAX.onError = function(e) { alert(HTML_AJAX_Util.quickPrint(e)); }
</script>
<style type="text/css">
body {
color: #24006B;
}
h2 {
text-align: center;
color: #330099;
}
#guestbookForm, #guestbookList {
width: 65%;
margin-right: auto;
margin-left: auto;
padding: 1.5em;
margin-top: 10px;
background-color: #D5BFFF;
border: 4px double #FFCC00;
}
fieldset, div.entry {
background-color: #FFF2BF;
border: 4px double #330099;
padding: 0.5em;
}
legend {
color: #330099;
font-size: 0.8em;
font-style: italic;
}
label {
clear: both;
display: block;
float: left;
width: 20%;
text-align: right;
font-weight: bold;
}
input {
display: block;
float: left;
width: 40%;
margin: 0 0.5em 0.5em 0.5em;
background-color: #B38F00;
border: 1px solid #AA80FF;
color: #330099;
}
input:focus, textarea:focus {
background-color: #D5BFFF;
border: 1px solid #B38F00;
}
textarea {
display: block;
float: left;
width: 40%;
height: 10em;
margin: 0 0.5em 0.5em 0.5em;
background-color: #B38F00;
border: 1px solid #AA80FF;
color: #330099;
}
input[type="submit"] {
display: block;
width: auto;
float: none;
margin-right: auto;
margin-left: auto;
font-size: 1.5em;
font-weight: bold;
background-color: #330099;
color: #FFCC00;
border: 3px double #FFE680;
}
.error {
color: #CC0000;
font-weight: bold;
float: left;
}
.small {
font-size: 0.8em
}
</style>
</head>
<body>
<?php //eventually ajax_helper should set this up for you, it's not done yet?>
<script type="text/javascript">
function sendguestbook(form) {
var remoteguestbook = new guestbook();
var payload = new Object();
for(var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name) {
payload[form.elements[i].name] = form.elements[i].value;
}
}
remoteguestbook.newEntry(payload);
return false;
}
function clearguestbook() {
var remoteguestbook = new guestbook();
remoteguestbook.clearGuestbook();
}
function deleteentry(id) {
var remoteguestbook = new guestbook();
remoteguestbook.deleteEntry(id);
}
function editentry(id) {
var remoteguestbook = new guestbook();
remoteguestbook.editEntry(id);
}
function updateselect(id) {
var remoteguestbook = new guestbook();
remoteguestbook.updateSelect(id);
}
</script>
<h2>Welcome to the Guestbook</h2>
<div id="guestbookList">
<?php
if (isset($_SESSION['entries'])) {
foreach($_SESSION['entries'] as $key => $data) {
echo '<div class="entry" id="entry'.$key.'">'
.'<h3><a href="mailto:'.$data->email.'">'.$data->name.'</a></h3>';
if(!empty($data->website))
{
echo '<a href="http://'.$data->website.'">'.$data->website.'</a><br />';
}
echo '<p>'.$data->comments.'</p>'
.'<div class="small">Posted: '.$data->date.' | '
.'<a href="#" onclick="editentry('.$key.');">Edit</a> | '
.'<a href="#" onclick="deleteentry('.$key.');">Delete</a></div>'
.'</div>';
}
}
?>
</div>
<div><a href="#" onclick="clearguestbook(this);">Clear Guestbook</a></div>
<form id="guestbookForm" action="index.php" method="post" onsubmit="sendguestbook(this); return false;">
<fieldset>
<legend>Leave Your Comments</legend>
<label for="name">Name: </label><input name="name" id="name" />
<label for="email">Email: </label><input name="email" id="email" />
<label for="website">Website: </label><input name="website" id="website" />
<label for="comments">Comments: </label><textarea name="comments" id="comments"></textarea>
<br style="clear: both" />
<input type="submit" id="submit" name="submit" value="Add Comments" />
</fieldset>
</form>
<p>Fill a select item with a list of options - tests the HTML_AJAX_Action::replaceNode and HTML_AJAX_Action::createNode methods</p>
<form id="testing" action="index.php" method="post" onsubmit="return false;">
<div>
<a href="#" onclick="updateselect('replaceme');">Gimme some options</a>
<select id="replaceme">
<option name="dog" id="dog">Dog</option>
</select>
</div>
</form>
</body>
</html>

View File

@@ -0,0 +1,52 @@
<?php
/**
* Example of Using HTML_AJAX_Action see support/testHaa.class.php
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// include the helper class
require_once 'HTML/AJAX/Helper.php';
// create an instance and set the server url
$ajaxHelper = new HTML_AJAX_Helper();
$ajaxHelper->serverUrl = 'auto_server.php';
$ajaxHelper->jsLibraries[] = array('haserializer');
$ajaxHelper->stubs[] = 'testHaa';
?>
<html>
<head>
<?php
echo $ajaxHelper->setupAJAX();
?>
<script type="text/javascript">
var remote = new testHaa();
</script>
<style type="text/css">
.test {
color: red;
}
</style>
</head>
<body>
<div id="test">
I'm some test content
</div>
<ul>
<li><a href="#" onclick="remote.updateClassName()">Update className</a></li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,59 @@
<?php
/**
* Example of Using HTML_AJAX_Helper
*
* HTML_AJAX_Helper takes care of basic JavaScript and HTML generation that is needed in many AJAX requests
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// include the helper class
require_once 'HTML/AJAX/Helper.php';
// create an instance and set the server url
$ajaxHelper = new HTML_AJAX_Helper();
$ajaxHelper->serverUrl = 'auto_server.php';
$ajaxHelper->jsLibraries[] = 'customLib';
?>
<html>
<head>
<?php
// output a javascript neded to setup HTML_AJAX
// by default this is all the libraries shipped with HTML_AJAX, take a look at $ajaxHelper->jsLibraries to edit the list
echo $ajaxHelper->setupAJAX();
?>
</head>
<body>
<?php
// output a custom loading message
echo $ajaxHelper->loadingMessage("Waiting on the Server ...");
?>
<div id="updateTarget">I'm an update Target</div>
<?php
// update the element using ajax
echo $ajaxHelper->updateElement('updateTarget',array('test','echo_string','Some text to echo'),'replace',true);
?>
<p>Was this page loaded using AJAX: <?php var_dump($ajaxHelper->isAJAX()); ?></p>
Below is the output of HTML_AJAX_Helper::isAJAX() on content loaded from AJAX
<div id="updateTarget2"></div>
<?php
echo $ajaxHelper->updateElement('updateTarget2','support/isajax.php','replace',true);
?>
</body>
</html>
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
?>

View File

@@ -0,0 +1,92 @@
<html>
<head>
<title>HTML_AJAX 0.5.2 Examples</title>
</head>
<body>
<h1>HTML_AJAX 0.5.2 Examples</h1>
<p>
These are examples showing the basics of using HTML_AJAX
</p>
<p>
These examples show off many of the features of HTML_AJAX, but you'll find them most useful as a learning tool.
Reading through the commented code as you view the examples in your browser.
</p>
<p>
These examples are available online at: http://bluga.net/projects/HTML_AJAX or in your local PEAR install in the documentation dir.
On most Linux systems the location is /usr/share/pear/docs/HTML_AJAX/examples/
You can find the location of your PEAR documentation dir running
<code>pear config-get doc_dir</code>
</p>
<p>The term proxy in these examples refers to a javascript class that is generated and has functions that map to the eqivalent php class.
These proxy classes work much in the same way as a SOAP proxy class that is generated from wsdl.
</p>
<p>
Front end files for examples, you can actually run these and see some example output
</p>
<ul>
<li><a href='proxyless_usage.php'>proxyless_usage.php</a> - Using HTML_AJAX in standalone mode, possible doesn't require PHP or any backend HTML_AJAX classes</li>
<li><a href='proxy_usage_inline_javascript.php'>proxy_usage_inline_javascript.php</a> - Single file proxy style usage</li>
<li><a href='proxy_usage_server.php'>proxy_usage_server.php</a> - Multi-file proxy usage, either server file could be used with this example</li>
<li><a href='queue_usage.php'>queue_usage.php</a> - An example of using a queue to manage ajax calls, a simple live search example</li>
<li><a href='slow_livesearch.php'>slow_livesearch.php</a> - An example showing how the ordered queue can be used to manage high latency</li>
<li><a href='helper_usage.php'>helper_usage.php</a> - An example showing the basics of the helper api</li>
<li><a href='form.php'>form.php</a> - Basic AJAX form submission example</a></li>
<li><a href='action_usage.php'>action_usage.php</a> - Basic HTML_AJAX_Action usage</a></li>
<li><a href='xml_usage.php'>xml_usage.php</a> - Basic XML serializer usage</a></li>
</ul>
<p>Real Life Examples</p>
<ul>
<li><a href='login/index.php'>login/index.php</a> - An example creating an AJAX driven login</a></li>
<li><a href='review/index.php'>review/index.php</a> - A simple live review system, AJAX form submission and click to edit</a></li>
<li><a href='guestbook/index.php'>guestbook/index.php</a> - A simple guestbook system, uses action system so you never write a line of javascript</a></li>
<li><a href='shoutbox.php'>shoutbox.php</a> - How to use AJAX form submission</a></li>
</ul>
<p>
2 server examples are provided, both provide the same output but the auto_server example has code to help you deal with managing multiple ajax classes
</p>
<ul>
<li>server.php - Basic server operation, serving ajax calls and client lib requests</li>
<li>auto_server.php - Advanced server operation, only create php classes as needed</li>
<li><a href='server.php?client=util,main'>server.php?client=util,main</a> - server.php generating a javascript file with the main and util libs in it</li>
<li><a href='auto_server.php?stub=test2'>server.php?stub=test2</a> - auto_server.php generating a javascript file a which contains a generated proxy class for the test2 php class</li>
<li><a href='auto_server.php?stub=all'>server.php?stub=all</a> - auto_server.php generating a javascript file which contains proxies for all the php classes registered with it</li>
</ul>
<p>
Examples files showing howto use HTML_AJAX_Util javascript class
</p>
<ul>
<li><a href='tests/js_utils_vardump.php'>js_utils_vardump.php</a> - Shows the output of HTML_AJAX_Util.varDump() and compares its against PHP's var_dump
</ul>
<p>
Other Example files:
</p>
<ul>
<li><a href='tests/test_speed.php'>test_speed.php</a> - A basic setup for measuring the speed of calls</li>
<li><a href='tests/test_priority.php'>test_priority.php</a> - A basic test showing how Priority queue works</li>
<li><a href='tests/serialize.php.examples.php'>serialize.php.examples.php</a> - Internal tests for the php serialize format serializer</li>
<li><a href='tests/serialize.url.examples.php'>serialize.url.examples.php</a> - Internal tests for the urlencoded format serializer</li>
<li><a href='tests/setInnerHTML.php'>setInnerHTML.php</a> - Tests used to verify the operation of HTML_AJAX_Util.setInnerHTML</li>
<li><a href='tests/duplicateJSLib.php'>duplicateJSLib.php</a> - Tests used to verify that HTML_AJAX_Server is removing duplicate JS libraries from client generation correctly</li>
<li><a href='tests/behaviorSpeed.php'>behaviorSpeed.php</a> - Tests used to see how fast the JavaScript behavior code runs.</li>
<li><a href='interceptors.php'>interceptors.php</a> - Interceptors test</a></li>
</ul>
<p>
Javascript and Html Examples:
</p>
<ul>
<li><a href="tests/test_behavior.html">test_behavior.html</a> - A short overview of how to use behavior.js. Behavior uses css selectors to apply javascript behaviors without throwing lots of javascript handlers into your html.</li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,40 @@
<?php
/**
* HTML_AJAX_Server with a register itnerceptor class
*
* The server responds to ajax calls and also serves the js client libraries, so they can be used directly from the PEAR data dir
* 304 not modified headers are used when server client libraries so they will be cached on the browser reducing overhead
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2007 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// include the server class
include 'HTML/AJAX/Server.php';
// include the test class will be registering
include 'support/test.class.php';
include 'support/test2.class.php';
include 'support/interceptor.php';
// create our new server
$server = new HTML_AJAX_Server();
// register an instance of the class were registering
$test = new test();
$server->registerClass($test,'test');
$test2 = new test2();
$server->registerClass($test2,'test2');
$server->ajax->packJavaScript = true;
$server->ajax->setInterceptor(new Interceptor());
$server->handleRequest();
?>

View File

@@ -0,0 +1,67 @@
<?php
/**
* Front end for interceptor examples, see support/interceptor.php for the interceptor class that is being used, and interceptorServer.php for how to register one
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
?><html>
<head>
<script type='text/javascript' src="interceptorServer.php?client=all"></script>
<script type='text/javascript' src="interceptorServer.php?stub=all"></script>
<script type='text/javascript'>
// definition of the callback javascript class, used to handle async requests
var callback = {
test1: function(result) {
document.getElementById('target').innerHTML = HTML_AJAX_Util.varDump(result);
},
test2: function(result) {
document.getElementById('target').innerHTML = HTML_AJAX_Util.varDump(result);
},
test3: function(result) {
document.getElementById('target').innerHTML = HTML_AJAX_Util.varDump(result);
}
}
// function used to clear out the target div
function clearTarget() {
document.getElementById('target').innerHTML = 'clear';
}
HTML_AJAX.onError = function(e) {
document.getElementById('errors').innerHTML = HTML_AJAX_Util.varDump(e);
}
</script>
</head>
<body>
<script type="text/javascript">
// create a proxy in async mode
var testProxy = new test(callback);
var test2Proxy = new test2({test: function(result) { document.getElementById('target').innerHTML = HTML_AJAX_Util.varDump(result); }});
// run a sync call and set its results to the target div
</script>
<ul>
<li><a href="javascript:clearTarget()">Clear Target</a></li>
<li><a href="javascript:testProxy.test1('One')">Run test::test1, matches interceptor for specific method</a></li>
<li><a href="javascript:testProxy.test2('Two')">Run test::test2, matches interceptor for class</a></li>
<li><a href="javascript:testProxy.test3('Three')">Run test::test3, matches interceptor for class</a></li>
<li><a href="javascript:test2Proxy.test('Four')">Run test2::test, matches global interceptor</a></li>
</ul>
<div style="white-space: pre; padding: 1em; margin: 1em; width: 600px; height: 300px; border: solid 2px black; overflow: auto;" id="target">Target</div>
<div style="white-space: pre; padding: 1em; margin: 1em; width: 600px; height: 300px; border: solid 2px black; overflow: auto;" id="errors">Errors</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,147 @@
<?php
require_once 'HTML/AJAX/Helper.php';
$objAjaxHelper = new HTML_AJAX_Helper();
$objAjaxHelper->serverUrl = './php/auto_server.php';
$objAjaxHelper->jsLibraries[] = 'haserializer';
$objAjaxHelper->stubs[] = 'login';
$strAjaxScript = $objAjaxHelper->setupAJAX();
?>
<html>
<head>
<title>Form validation (v2) with HTML_AJAX</title>
<!-- HTML_AJAX -->
<?php echo $strAjaxScript ?>
<script type="text/javascript">
/**
* Basic page initialization
*/
function initPage() {
// Set up the labels so they know the associated input elements
var arrLabels = document.getElementsByTagName("label");
for (var i=0; i < arrLabels.length; i++) {
var objTemp = arrLabels[i];
var strFor = objTemp.getAttribute('for');
// Fix the attributes
if (strFor != '') {
// Set the ID of the label
objTemp.setAttribute('id', 'l' + strFor);
// Save the original class of the label (if any)
objTemp.setAttribute('classOrig', objTemp.getAttribute('class'));
}
}
// Set the focus on the first element
document.getElementById('username').focus();
}
/**
* Sets the class of an element (build for this example)
*/
function setElement(strElement, blnValidated) {
// Update the label
var objElem = document.getElementById('l' + strElement);
if (objElem) {
if (blnValidated == 1) {
strClass = objElem.getAttribute('classOrig');
} else {
strClass = 'error';
}
objElem.setAttribute('class', '' + strClass);
}
return false;
}
/**
* Shows or hides an element
*/
function toggleElement(strElement, blnVisible) {
var objStyle = document.getElementById(strElement).style;
if (objStyle) {
objStyle.display = (blnVisible == 1) ? 'block' : 'none';
}
}
/**
* Login function
*/
function doLogin() {
// Create object with values of the form
var objTemp = new Object();
objTemp['username'] = document.getElementById('username').value;
objTemp['password'] = document.getElementById('password').value;
objTemp['email'] = document.getElementById('email').value;
// Create a dummy callback so the loading box will appear...
var objCallback = { validate: function() {} };
// Send the object to the remote class
var objLogin = new login(objCallback);
objLogin.validate(objTemp);
}
</script>
<!-- STYLESHEET -->
<link rel="stylesheet" type="text/css" href="login.css" />
</head>
<body>
<!-- THE ERROR MESSAGES -->
<div id="messages" class="errorbox"></div>
<br />
<!-- THE FORM -->
<form action="" method="post" onSubmit="doLogin(); return false;">
<fieldset style="width: 500px;">
<legend>Enter your login details</legend>
<table width="400" border="0" cellspacing="0" cellpadding="2">
<tr>
<td><label for="username">Username:</label></td>
<td><input type="text" name="username" id="username" size="40" tabindex="1"></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="text" name="password" id="password" size="40" tabindex="2"></td>
</tr>
<tr>
<td><label for="email">E-mail:</label></td>
<td><input type="text" name="email" id="email" size="40" tabindex="3"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" value=" login ">&nbsp;<input type="reset" value=" reset "></td>
</tr>
</table>
</fieldset>
</form>
<div id="HTML_AJAX_LOADING" class="AjaxLoading">Please wait while loading</div>
<p>
<strong>This sample is an updated version of the original login sample</strong>:<br />
&#0187; It now uses the new HTML_AJAX_Action class.<br>
&#0187; The initialization of the labels and their input elements is done by Javascript to clean up the page (function: initPage()).<br>
<br>
<strong>Design notes</strong>:<br>
&#0187; The attribute &quot;style.display&quot; cannot be set from php code. Don't know why though. I created a wrapper function for it called &quot;toggleElement&quot; which does the trick. Funny enough when i execute thesame lines of script using -&gt;insertScript nothing happens.<br>
&#0187; You have to add a dummy callback in order to show the loading progress bar.<br>
&#0187; Enter username &quot;peter&quot;, password &quot;gabriel&quot; and any valid e-mail adress to see a messagebox.<br>
<br>
&copy; under LGPL @ 21 nov 2005 by www.webunity.nl<br>
</p>
<script type="text/javascript">
if (document.getElementsByTagName) {
initPage();
} else {
alert('This sample requires the DOM2 "getElementsByTagName" function.');
}
</script>
</body>
</html>
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
?>

View File

@@ -0,0 +1,66 @@
/* --------------------------------------------------------------------------------------------------
General styles
------------------------------------------------------------------------------------------------- */
body, table {
color: #000000;
font-size: 70%;
font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;
}
table, fieldset {
font-size: 1em;
}
body, td, th {
line-height: 140%;
}
td, th {
vertical-align: top;
}
form, ul {
margin: 0;
padding: 0;
}
legend {
color: #0046D5;
font-weight: bold;
padding-right: 8px;
margin-bottom: 5px;
}
ol, ul {
margin-left: 6px;
padding-left: 15px;
}
/* --------------------------------------------------------------------------------------------------
Custom styles
------------------------------------------------------------------------------------------------- */
.errorbox {
padding: 8px;
border: 1px solid #ff0000;
display: none;
}
label {
color: #006fcc;
font-weight: bold;
}
label.error {
color: #ff0000;
font-weight: bold;
}
.AjaxLoading {
position: absolute;
top: 10px;
right: 10px;
background-color: red;
width: 80px;
padding: 4px;
display: none;
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* Very simple form script with error handling.
*
* @category HTML
* @package AJAX
* @author Gilles van den Hoven <gilles@webunity.nl>
* @copyright 2005 Gilles van den Hoven
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// include the server class
include 'HTML/AJAX/Server.php';
// extend HTML_AJAX_Server creating our own custom one with init{ClassName} methods for each class it supports calls on
class LoginServer extends HTML_AJAX_Server {
// this flag must be set to on init methods
var $initMethods = true;
// init method for the test class, includes needed files an registers it for ajax
function initLogin() {
include 'class.login.php';
$this->registerClass(new login(), 'login', array('validate'));
}
}
// create an instance of our test server
$server = new LoginServer();
// handle requests as needed
$server->handleRequest();
?>

View File

@@ -0,0 +1,128 @@
<?php
// Includes
require_once 'HTML/AJAX/Action.php';
// Error messages
define('ERR_USERNAME_EMPTY', 'You forgot to enter a username, please try again');
define('ERR_USERNAME_INVALID', 'The username you entered is invalid. Please try "peter" (without quotes)');
define('ERR_PASSWORD_EMPTY', 'You forgot to enter a password, please try again');
define('ERR_PASSWORD_INVALID', 'The password you entered is invalid. Please try "gabriel" (without quotes)');
define('ERR_EMAIL_EMPTY', 'You forgot to enter an e-mail address');
define('ERR_EMAIL_INVALID', 'The e-mail address you entered is invalid. Please enter a valid e-mail address.');
/**
* Login class used in the "login form" example
* Please note: Constructors and private methods marked with _ are never exported in proxies to JavaScript
*
* @category HTML
* @package AJAX
* @author Gilles van den Hoven <gilles@webunity.nl>
* @copyright 2005 Gilles van den Hoven
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
class login {
/**
* PHP5 requires a constructor
*/
function login() {
}
/**
* Checks the proper syntax
*/
function _checkEmail($strEmail) {
return (preg_match( '/^[A-Z0-9._-]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z.]{2,6}$/i' , $strEmail));
}
/**
* Checks if the passed values are correct.
*
* @param array the form object
*/
function validate($arrayForm) {
//--------------------------------------------------
// Initialize function
//--------------------------------------------------
// Array to hold the messages
$arrMessages = array();
// Set all form values that they validated. Could be improved by analyzing
// the values passed in $objForm and setting values accordingly.
$arrValidated = array();
$arrValidated['username'] = true;
$arrValidated['password'] = true;
$arrValidated['email'] = true;
// Never trust the values passed by users :)
$objForm = new stdClass();
$objForm->username = trim($arrayForm['username']);
$objForm->password = trim($arrayForm['password']);
$objForm->email = trim($arrayForm['email']);
//--------------------------------------------------
// Check values
//--------------------------------------------------
// Check username
if ($objForm->username == '') {
$arrMessages[] = ERR_USERNAME_EMPTY;
$arrValidated['username'] = false;
} else if ($objForm->username != 'peter') {
$arrMessages[] = ERR_USERNAME_INVALID;
$arrValidated['username'] = false;
}
// Check password
if ($objForm->password == '') {
$arrMessages[] = ERR_PASSWORD_EMPTY;
$arrValidated['password'] = false;
} else if ($objForm->password != 'gabriel') {
$arrMessages[] = ERR_PASSWORD_INVALID;
$arrValidated['password'] = false;
}
// Check email
if ($objForm->email == '') {
$arrMessages[] = ERR_EMAIL_EMPTY;
$arrValidated['email'] = false;
} else if ($this->_checkEmail($objForm->email) == false) {
$arrMessages[] = ERR_EMAIL_INVALID;
$arrValidated['email'] = false;
}
//--------------------------------------------------
// Finalize function
//--------------------------------------------------
// Create the message list
$strMessages = '';
if (count($arrMessages) > 0) {
$strMessages = '<ul>';
foreach ($arrMessages as $strTemp) {
$strMessages.= '<li>'.$strTemp.'</li>';
}
$strMessages.= '</ul>';
}
// Create a response object
$objResponse = new HTML_AJAX_Action();
// Assign the messages
$objResponse->assignAttr('messages', 'innerHTML', $strMessages);
$objResponse->insertScript("toggleElement('messages', ".(($strMessages != '') ? 1 : 0).");");
// Generate the scripts to update the form elements' label and input element
foreach ($arrValidated as $strKey => $blnValue) {
$objResponse->insertScript("setElement('".$strKey."', ".(($blnValue) ? '1' : '0').");");
}
// Test for no messages
if ($strMessages == "") {
$objResponse->insertAlert("Well done chap!");
}
// And ready! :)
return $objResponse;
}
}
?>

View File

@@ -0,0 +1 @@
["argument1","argument2","argument3"]

View File

@@ -0,0 +1,74 @@
<?php
require_once 'HTML/AJAX/Server.php';
class Foo {
function bar()
{
return 'hello';
}
}
function foobar()
{
return 'hello';
}
// start server
$server = new HTML_AJAX_Server();
// register normal function
$callback = 'foobar';
$server->registerPhpCallback($callback);
// register static method
$callback = array('Foo', 'bar');
$server->registerPhpCallback($callback);
// register object method
$foo = new Foo;
$callback = array($foo, 'bar');
$server->registerPhpCallback($callback);
// handle the request
if ($server->handleRequest()) {
exit;
}
?>
<html>
<head>
<script type='text/javascript' src="?client=all&amp;stub=all"></script>
<script type="text/javascript" language="Javascript">
<!--
HTML_AJAX.defaultServerUrl = 'php_callback.php';
function testCallPhpCallback(cb)
{
HTML_AJAX.callPhpCallback(cb, showResult);
}
function showResult(result)
{
alert(result);
}
var foo = new foo;
//-->
</script>
</head>
<body>
using HTML_AJAX.callPhpCallback()
<ul>
<li><a href="javascript:testCallPhpCallback('foobar')">normal function</a></li>
<li><a href="javascript:testCallPhpCallback(['Foo', 'bar'])">static method</a></li>
<li><a href="javascript:testCallPhpCallback([foo, 'bar'])">object method</a></li>
</ul>
exported
<ul>
<li><a href="javascript:alert(foo.bar())">object method</a></li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,166 @@
<?php
/**
* Example of Using HTML_AJAX in proxy operation
*
* All AJAX calls are handled by this same file and the proxy js is outputed in a js block directly in this script
* This is a use case very similar to Sajax (Sajax registers functions not objects)
*
* The only needed interaction is creation of a new object from the proxy defintion, all AJAX calls happen transparently from
*
* If you want to perform async calls a callback object must be passed to the constructor of the object
*
* The client JavaScript library is provided by server.php, you could also copy HTML_AJAX.js (all js files combined) or the seperate js files into your webroot
* from the PEAR data dir and src them directly
*
* This example also registers a custom error handler, without this handler errors float out of the app as an Exception
*
* An example debugging event listener is also shown
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// include the main HTML_AJAX class
include 'HTML/AJAX.php';
// our simple test class
include 'support/test.class.php';
// create an instance of HTML_AJAX
$ajax = new HTML_AJAX();
// register an instance of the test class
$ajax->registerClass(new test());
// handle and ajax call, if one is made die, else continue processing
if ($ajax->handleRequest()) {
die();
}
?><html>
<head>
<!-- the entire client library can be retreived in one call using the all keyword, or each piece can be requested like below -->
<script type='text/javascript' src="server.php?client=Main"></script>
<script type='text/javascript' src="server.php?client=Dispatcher"></script>
<script type='text/javascript' src="server.php?client=HttpClient"></script>
<script type='text/javascript' src="server.php?client=Request"></script>
<script type='text/javascript' src="server.php?client=JSON"></script>
<script type='text/javascript' src="server.php?client=iframe"></script>
<script type='text/javascript' src="server.php?client=loading"></script>
<script type='text/javascript'>
<?php
// generate proxy definition javascript for all registered class
echo $ajax->generateJavascriptClient();
?>
// definition of the callback javascript class, used to handle async requests
function callback() {}
callback.prototype = {
echo_string: function(result) {
document.getElementById('target').innerHTML = result;
},
slow_echo_string: function(result) {
document.getElementById('target').innerHTML = result;
},
error_test: function(result) {
document.getElementById('target').innerHTML = result;
}
}
// function used to clear out the target div
function clearTarget() {
document.getElementById('target').innerHTML = 'clear';
document.getElementById('eventLog').innerHTML = 'clear';
document.getElementById('error').innerHTML = 'clear';
}
// register a custom error handler
HTML_AJAX.onError = function(e) {
msg = "\n\n";
for(var i in e) {
msg += i + ':' + e[i] +"\n";
}
document.getElementById('error').innerHTML += msg;
}
// register custom event handlers, but lets keep the old ones so we still have that automatic loading message
var Open = HTML_AJAX.Open;
var Load = HTML_AJAX.Load;
HTML_AJAX.Open = function(request) {
Open(request);
document.getElementById('eventLog').innerHTML += "Open: "+request.className+'::'+request.methodName+"\n";
}
HTML_AJAX.Send = function(request) {
document.getElementById('eventLog').innerHTML += "Send: "+request.className+'::'+request.methodName+"\n";
}
HTML_AJAX.rogress = function(request) {
document.getElementById('eventLog').innerHTML += "Progress: "+request.className+'::'+request.methodName+"\n";
}
HTML_AJAX.Load = function(request) {
Load(request);
document.getElementById('eventLog').innerHTML += "Load: "+request.className+'::'+request.methodName+"\n";
}
</script>
</head>
<body>
<script type="text/javascript">
// create a proxy in sync mode
var syncProxy = new test();
// create a proxy in async mode
var asyncProxy = new test(new callback());
// run a sync call and set its results to the target div
function syncCall() {
document.getElementById('target').innerHTML = syncProxy.echo_string("I'm a sync call");
}
// run a sync call, callback class will handle its results
function asyncCall() {
asyncProxy.echo_string("I'm a async call");
}
// run a sync call, callback class will handle its results
// the purpose of this slow call is to show off the built in loading messaging
function slowAsyncCall() {
asyncProxy.slow_echo_string("I'm a slow async call");
}
// same thing, notice how it locks up your browser in Firefox you can't switch to another tab
function slowSyncCall() {
document.getElementById('target').innerHTML = syncProxy.slow_echo_string("I'm a slow sync call");
}
// run a sync call, callback class will handle its results
function serverErrorExample() {
asyncProxy.error_test("I'm an error generated by trigger error in test.class.php");
}
// same as above, shown for completeness
function serverErrorSyncExample() {
document.getElementById('target').innerHTML = syncProxy.error_test("I'm an error generated by trigger error in test.class.php");
}
</script>
<ul>
<li><a href="javascript:clearTarget()">Clear Target</a></li>
<li><a href="javascript:syncCall()">Run Sync Echo call</a></li>
<li><a href="javascript:asyncCall();">Run Async Echo call</a></li>
<li><a href="javascript:slowAsyncCall();">Run Slow Async Echo call (sleep on server to emulate slow processing)</a></li>
<li><a href="javascript:slowSyncCall();">Run Slow Sync Echo call (notice how it locks your browser)</a></li>
<li><a href="javascript:serverErrorExample();">Run a call where an error is generated on the server (Async)</a></li>
<li><a href="javascript:serverErrorSyncExample();">Run a call where an error is generated on the server (Sync)</a></li>
</ul>
<div style="white-space: pre; padding: 1em; margin: 1em; width: 300px; height: 400px; border: solid 2px black; overflow: auto; float: right;" id="error">Error Target</div>
<div style="white-space: pre; padding: 1em; margin: 1em; width: 500px; height: 300px; border: solid 2px black; overflow: auto;" id="target">Target</div>
<div style="white-space: pre; padding: 1em; margin: 1em; width: 500px; height: 400px; border: solid 2px black; overflow: auto;" id="eventLog">Event Log
</div>
</body>
</html>

View File

@@ -0,0 +1,123 @@
<?php
/**
* Example of Using HTML_AJAX in proxy operation
*
* All AJAX calls are handled by the auto_server.php file, server.php could also be used, the differences between the two are covered in those files
* This is a use case very similar to JPSpan (JPSpan only has a server.php equivalent)
*
* The only needed interaction is creation of a new object from the proxy defintion, all AJAX calls happen transparently from there
*
* If you want to perform async calls a callback object must be passed to the constructor of the object
*
* The client JavaScript library is provided by auto_server.php, you could also copy HTML_AJAX.js (all js files combined) or the seperate js files into your webroot
* from the PEAR data dir and src them directly. You can use multiple includes of the component files or use the all flag to get them all at once.
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// set a cookie so we always have an example cookie for the test
setcookie('testcookie',"Doesn't taste as good as a peanut butter cookie");
?><html>
<head>
<!-- These two calls can be combined into one call if wanted, but its not recomended since it will hurt caching as you might want stubs of multiple classes -->
<script type='text/javascript' src="auto_server.php?client=all"></script>
<!-- Stub is passed the class you want the proxy definition for, you can also use all to get every registered class but that create those auto server
has to instanciate every class where here only the class used on this page has to be instanciated -->
<script type='text/javascript' src="auto_server.php?stub=test"></script>
<script type='text/javascript'>
// definition of the callback javascript class, used to handle async requests
function callback() {}
callback.prototype = {
echo_string: function(result) {
document.getElementById('target').innerHTML = result;
},
cookies: function(result) {
var ret = "";
for(var i in result) {
ret += i+':'+result[i]+"\n";
}
document.getElementById('target').innerHTML = ret;
},
echo_data: function(result) {
document.getElementById('target').innerHTML = HTML_AJAX_Util.varDump(result);
},
unicode_data: function(result) {
document.getElementById('target').innerHTML = HTML_AJAX_Util.varDump(result);
},
dump: function(result) {
document.getElementById('target').innerHTML = result;
}
}
// function used to clear out the target div
function clearTarget() {
document.getElementById('target').innerHTML = 'clear';
}
</script>
</head>
<body>
<script type="text/javascript">
// create a proxy in sync mode
var syncProxy = new test();
// create a proxy in async mode
var asyncProxy = new test(new callback());
// run a sync call and set its results to the target div
function syncCall() {
document.getElementById('target').innerHTML = syncProxy.echo_string("I'm a sync call");
}
// run a sync call, callback class will handle its results
function asyncCall() {
asyncProxy.echo_string("I'm a async call");
}
function unicodeTest() {
//asyncProxy.echo_data({'suggestion': ['Français', 'caractères']});
asyncProxy.echo_data({"suggestion":["Fran\u00e7ais","caract\u00e8res"]});
}
function unicodeTest2() {
asyncProxy.unicode_data();
}
function cookieTest() {
asyncProxy.cookies();
}
function assocTest() {
asyncProxy.dump({a: 'first var', b: 'second var'});
}
</script>
<ul>
<li><a href="javascript:clearTarget()">Clear Target</a></li>
<li><a href="javascript:syncCall()">Run Sync Echo call</a></li>
<li><a href="javascript:asyncCall();">Run Async Echo call</a></li>
<li><a href="javascript:unicodeTest();">Check ability to round trip utf-8 JSON data</a></li>
<li><a href="javascript:unicodeTest2();">Check ability to recieve utf-8 JSON data</a></li>
<li><a href="javascript:assocTest();">Check ability to decode js hashes into PHP associative arrays using JSON</a></li>
<li><a href="javascript:cookieTest();">View Cookies</a></li>
</ul>
<div style="white-space: pre; padding: 1em; margin: 1em; width: 600px; height: 300px; border: solid 2px black; overflow: auto;" id="target">Target</div>
<div>
Runing view Cookies should show you these same cookies being returned by the AJAX call<br>
If the lists don't match, try reloading this page, it sets a test cookie, but we can't see it on the PHP side until the client returns it on a test.
<pre>
<?php
var_dump($_COOKIE);
?>
</pre>
</div>
</body>
</html>

View File

@@ -0,0 +1,149 @@
<?php
/**
* Example of Using HTML_AJAX in proxyless operation
*
* This is the simplest way to use HTML_AJAX if your just using grab and replace functions you don't even need a server
* You need every javascript file except JSON which is optional and is only needed if your using that encoding
*
* The proxyless api is provided by Main.js
*
* There are 4 main methods and 2 properties to the proxyless api, they all exist as static methods on HTML_AJAX
* HTML_AJAX.grab(url)
* HTML_AJAX.post(url,payload)
* HTML_AJAX.replace(id,url) or HTML_AJAX.replace(id,class,method,arg1,arg2,etc)
* HTML_AJAX.call(class,method,callback,arg1,arg2,etc)
*
* HTML_AJAX.defaultServerUrl = 'serverurl';
* HTML_AJAX.defaultEncoding = 'Null';
*
* The api is demonstrated below, server.php is used for call examples and to load the needed js files
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
?>
<html>
<head>
<script type='text/javascript' src="server.php?client=Util"></script>
<script type='text/javascript' src="server.php?client=main"></script>
<script type='text/javascript' src="server.php?client=dispatcher"></script>
<script type='text/javascript' src="server.php?client=HttpClient"></script>
<script type='text/javascript' src="server.php?client=Request"></script>
<script type='text/javascript' src="server.php?client=json"></script>
<script type='text/javascript' src="server.php?client=loading"></script>
<script type='text/javascript' src="server.php?client=iframe"></script>
<script type='text/javascript' src="server.php?client=urlserializer"></script>
</head>
<body>
<script type="text/javascript">
function clearTarget() {
document.getElementById('target').innerHTML = 'clear';
}
// Add an error handler so we get an alert if any errors happen while making an AJAX call
HTML_AJAX.onError = function(e)
{
alert(HTML_AJAX_Util.varDump(e));
}
// Grab is the simplest usage of HTML_AJAX you use it to perform a request to a page and get its results back
// It can be used in either Sync mode where it returns directory or with a call back, both methods are shown below
var url = 'README';
function grabSync() {
document.getElementById('target').innerHTML = HTML_AJAX.grab(url);
}
function grabAsync() {
HTML_AJAX.grab(url,grabCallback);
}
function grabCallback(result) {
document.getElementById('target').innerHTML = result;
}
// POST lets you make simple POST requests to a url, if you use a hash {key:value,key2:value,etc} as the payload then the
// data will be automatically be urlencoded, making it look like a form submission to the server
// if the data is a string it will be sent as is
var postUrl = 'support/post_tester.php';
function postSync() {
document.getElementById('target').innerHTML = HTML_AJAX.post(postUrl,{dog:'bob',cat:'tigger'});
}
function postAsync() {
HTML_AJAX.post(postUrl,{dog:'bob',cat:'tigger'},grabCallback);
}
function postCallback(result) {
document.getElementById('target').innerHTML = result;
}
// replace can operate either against a url like grab or against a remote method
// if its going to be used against a remote method defaultServerUrl needs to be set to a url that is exporting the class its trying to call
// note that replace replace always works async
HTML_AJAX.defaultServerUrl = 'server.php';
function replaceUrl() {
HTML_AJAX.replace('target',url);
}
function replaceFromMethod() {
HTML_AJAX.replace('target','test','echo_string','Im a method call replacement');
}
function replaceFromMethodMulti() {
// Null encoding does not support multiple arguments, you have to use JSON for that
HTML_AJAX.defaultEncoding = 'JSON'; // set encoding to JSON encoding method
HTML_AJAX.replace('target','test','multiarg','argument1','argument2','argument3');
HTML_AJAX.defaultEncoding = 'Null'; // return it to default which is Null
}
// call is used to call a method on a remote server
// you need to set HTML_AJAX.defaultServerUrl to use it
// you might also want to set HTML_AJAX.defaultEncoding, options are Null and JSON, the server will autodetect this encoding from your content type
// but the return content type will be based on whatever the servers settings are
// You can use call in either Sync or Async mode depending on if you pass it a callback function
function callSync() {
HTML_AJAX.defaultEncoding = 'JSON'; // set encoding to JSON encoding method
document.getElementById('target').innerHTML = HTML_AJAX.call('test','echo_string',false,'Im text that was echoed');
HTML_AJAX.defaultEncoding = 'Null'; // return it to default which is Null
}
function callAsync() {
HTML_AJAX.call('test','echo_string',callCallback,'Im text that was echoed Async');
}
function callCallback(result) {
document.getElementById('target').innerHTML = result;
}
</script>
<ul>
<li><a href="javascript:clearTarget()">Clear Target</a></li>
<li><a href="javascript:grabSync()">Run Sync Grab Example</a></li>
<li><a href="javascript:grabAsync()">Run Async Grab Example</a></li>
<li><a href="javascript:postSync()">Run Sync Post Example</a></li>
<li><a href="javascript:postAsync()">Run Async Post Example</a></li>
<li><a href="javascript:replaceUrl()">Replace with content from a url</a></li>
<li><a href="javascript:replaceFromMethod()">Replace with content from a method call</a></li>
<li><a href="javascript:replaceFromMethodMulti()">Replace with content from a method call (multiple method arguments)</a></li>
<li><a href="javascript:callSync()">Sync Call</a></li>
<li><a href="javascript:callAsync()">ASync Call</a></li>
</ul>
<div style="white-space: pre; padding: 1em; margin: 1em; width: 600px; height: 300px; border: solid 2px black; overflow: auto;" id="target">Target</div>
</body>
</html>
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
?>

View File

@@ -0,0 +1,76 @@
<?php
/**
* Example of Using HTML_AJAX with a queue
*
* When using HTML_AJAX your actually always using a queue, its just its a simple one that always performs whatever actions its given immediately
* HTML_AJAX however provides other queues offering different modes of operation
*
* Currently the Queues are (class names are prefixed with: HTML_AJAX_Queue_):
* Immediate - Default make the request immediately
* Interval_SingleBuffer - Make request on an interval with holding just the last request between calls
*
* Interval_SingleBuffer is generally used for Live Search/Google Suggest type operations
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
?>
<html>
<head>
<script type='text/javascript' src="server.php?client=Util,main,dispatcher,httpclient,request,json,loading,iframe,queues"></script>
<script type='text/javascript' src="auto_server.php?stub=livesearch"></script>
</head>
<body>
<script type="text/javascript">
// callback hash, outputs the results of the search method
callback = {
search: function(result) {
var out = "<ul>";
// if we have object this works right, if we have an array we get a problem
// if we have sparse keys will get an array back otherwise will get an array
for(var i in result) {
if (i != '______array') {
out += "<li>"+i+" = "+result[i]+"</li>";
}
}
out += "</ul>";
document.getElementById('target').innerHTML = out;
}
}
// setup our remote object from the generated proxy stub
var remoteLiveSearch = new livesearch(callback);
// we could change the queue by overriding the default one, but generally you want to create a new one
// set our remote object to use the rls queue
remoteLiveSearch.dispatcher.queue = 'rls';
// create the rls queue, with a 350ms buffer, a larger interval such as 2000 is useful to see what is happening but not so useful in real life
HTML_AJAX.queues['rls'] = new HTML_AJAX_Queue_Interval_SingleBuffer(350);
// what to call on onkeyup, you might want some logic here to not search on empty strings or to do something else in those cases
function searchRequest(searchBox) {
remoteLiveSearch.search(searchBox.value);
}
</script>
<p>This is a really basic LiveSearch example, type in the box below to find a fruit</p>
Search <input id="search" autocomplete="off" onkeyup="searchRequest(this)">
<div style="white-space: pre; padding: 1em; margin: 1em; width: 600px; height: 300px; border: solid 2px black; overflow: auto;" id="target">Target</div>
</body>
</html>
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
?>

View File

@@ -0,0 +1,36 @@
<?php
/**
* Server that exposes a class for doing a fake review
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// include the server class
include 'HTML/AJAX/Server.php';
// extend HTML_AJAX_Server creating our own custom one with init{ClassName} methods for each class it supports calls on
class ReviewServer extends HTML_AJAX_Server {
// this flag must be set to on init methods
var $initMethods = true;
// init method for the test class, includes needed files an registers it for ajax
function initReview() {
include 'review.class.php';
$this->registerClass(new review(),'Review',array('newReview','updateReview')); // specify methods so that we get case in php4
}
}
session_start();
// create an instance of our test server
$server = new ReviewServer();
// handle requests as needed
$server->handleRequest();
?>

View File

@@ -0,0 +1,136 @@
<?php
/**
* Almost real life example, show a list reviews, letting you add one, and then updating the list
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// include the helper class
require_once 'HTML/AJAX/Helper.php';
// create an instance and set the server url
session_start();
$ajaxHelper = new HTML_AJAX_Helper();
$ajaxHelper->serverUrl = 'auto_server.php';
$ajaxHelper->jsLibraries[] = 'JSON'; // not included in the default list before 0.2.6
?>
<html>
<head>
<?php
// output a javascript neded to setup HTML_AJAX
// by default this is all the libraries shipped with HTML_AJAX, take a look at $ajaxHelper->jsLibraries to edit the list
echo $ajaxHelper->setupAJAX();
// ajax helper should do this for you but it doesn't yet
?>
<script type="text/javascript" src="auto_server.php?stub=review"></script>
<script type="text/javascript">
var reviewCallback = {
// after a review we get a chunk of html that we can update the reviewList with
newReview: function(result) {
document.getElementById('reviewList').innerHTML += result;
},
// after a review is updated we get a chunk of html, replace a node from our lookup list with that
updateReview: function(result) {
var newdiv = document.createElement('div');
newdiv.innerHTML = result[1];
document.getElementById('reviewList').replaceChild(newdiv.firstChild,reviewCallback.nodeList[result[0]]);
},
nodeList: []
}
function sendReview(form) {
var remoteReview = new Review(reviewCallback);
var payload = new Object();
for(var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name) {
payload[form.elements[i].name] = form.elements[i].value;
}
}
// do any needed validation here
remoteReview.newReview(payload);
}
function updateReview(id,form) {
var remoteReview = new Review(reviewCallback);
var payload = new Object();
for(var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name) {
payload[form.elements[i].name] = form.elements[i].value;
}
}
// do any needed validation here
remoteReview.updateReview(id,payload);
}
function editReview(id,node) {
var form = document.getElementById('reviewForm').cloneNode(true);
form.onsubmit = function() { updateReview(id,this); return false; }
var data = new Object();
var divs = node.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
if (divs[i].className) {
data[divs[i].className] = divs[i].innerHTML;
}
}
for(var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name) {
form.elements[i].value = data[form.elements[i].name];
}
}
document.getElementById('reviewList').replaceChild(form,node);
reviewCallback.nodeList[id] = form;
}
</script>
<style type="text/css">
.name {
margin-top: 5px;
background-color: #ddd;
}
#reviewList {
width: 300px;
}
</style>
</head>
<body>
<h2>Add a new Review</h2>
<form id="reviewForm" onsubmit="sendReview(this); return false;" style="border: dotted 1px black">
Your Name: <input name="name"><br>
Your Review: <textarea name="review"></textarea><br>
<input type="submit">
</form>
<div id="reviewList">
<?php
if (isset($_SESSION['reviews'])) {
foreach($_SESSION['reviews'] as $key => $review) {
echo "<div onclick='editReview($key,this)'><div class='name'>$review->name</div><div class='review'>$review->review</div></div>\n";
}
}
?>
</div>
</body>
</html>
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
?>

View File

@@ -0,0 +1,33 @@
<?php
class Review {
// constructor won't be exported
function Review() {
if (!isset($_SESSION['reviews'])) {
$_SESSION['reviews'] = array();
}
}
// data is an array of objects
function newReview($data) {
// clean data, its coming from the client
$data['name'] = htmlentities($data['name']);
$data['review'] = htmlentities($data['review']);
$_SESSION['reviews'][] = $data;
$key = count($_SESSION['reviews'])-1;
return "<div onclick='editReview($key,this)'><div class='name'>$data[name]</div><div class='review'>$data[review]</div></div>";
}
function updateReview($key,$data) {
// clean data, its coming from the client
$data['name'] = htmlentities($data['name']);
$data['review'] = htmlentities($data['review']);
$_SESSION['reviews'][$key] = $data;
return array($key,"<div onclick='editReview($key,this)'><div class='name'>$data[name]</div><div class='review'>$data[review]</div></div>");
}
}
?>

View File

@@ -0,0 +1,36 @@
<?php
/**
* Simplest possible usage of HTML_AJAX_Server
*
* The server responds to ajax calls and also serves the js client libraries, so they can be used directly from the PEAR data dir
* 304 not modified headers are used when server client libraries so they will be cached on the browser reducing overhead
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
// include the server class
include 'HTML/AJAX/Server.php';
// include the test class will be registering
include 'support/test.class.php';
// create our new server
$server = new HTML_AJAX_Server();
// register an instance of the class were registering
$test =& new test();
$server->registerClass($test);
$server->ajax->packJavaScript = true;
// handle different types of requests possiblities are
// ?client=all - request for all javascript client files
// ?stub=classname - request for proxy stub for given class, can be combined with client but this may hurt caching unless stub=all is used
// ?c=classname&m=method - an ajax call, server handles serialization and handing things off to the proper method then returning the results
$server->handleRequest();
?>

View File

@@ -0,0 +1,67 @@
<?php
/**
* AJAX form submission, practical example
*
* @category HTML
* @package AJAX
* @author Arpad Ray <arpad@php.net>
* @copyright 2005 Arpad Ray
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
define('MESSAGE_FILE', 'messages.txt');
$messages = (is_readable(MESSAGE_FILE) ? unserialize(file_get_contents(MESSAGE_FILE)) : array());
function show_messages()
{
foreach ($GLOBALS['messages'] as $m) {
echo "<br>Name:{$m[0]}<br>Message:{$m[1]}<br><hr>";
}
}
function save_messages()
{
if ($h = @fopen(MESSAGE_FILE, 'wb')) {
$GLOBALS['messages'] = array_slice($GLOBALS['messages'], -5);
fwrite($h, serialize($GLOBALS['messages']));
fclose($h);
}
}
if (!empty($_POST)) {
if (!empty($_POST['name']) && !empty($_POST['message'])) {
$messages[] = array(
htmlspecialchars(strip_tags(substr($_POST['name'], 0, 10))),
htmlspecialchars(strip_tags(substr($_POST['message'], 0, 30)))
);
save_messages();
}
show_messages();
exit;
}
?><html>
<head>
<script type="text/javascript" src="server.php?client=all&amp;stub=all"></script>
</head>
<body>
<h1>Messages:</h1>
<div id="target">
<?php show_messages(); ?>
</div>
<form action="shoutbox.php" method="post" onsubmit="return !HTML_AJAX.formSubmit(this, 'target')">
<label>
Name:
<input type="text" name="name" id="name" />
</label>
<label>
Message:
<input type="text" name="message" id="message" />
</label>
<input type="submit" value="Submit" />
</form>
</body>
</html>

View File

@@ -0,0 +1,77 @@
<?php
/**
* Using the ordered queue to deal with high latency
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
session_start();
if (isset($_GET['latency'])) {
$_SESSION['sleep'] = $_GET['latency'];
}
?>
<html>
<head>
<script type='text/javascript' src="server.php?client=Util,main,dispatcher,httpclient,request,json,loading,iframe,orderedqueue"></script>
<script type='text/javascript' src="slow_server.php?stub=livesearch"></script>
</head>
<body>
<script type="text/javascript">
// callback hash, outputs the results of the search method
callback = {
search: function(result) {
var out = "<ul>";
// if we have object this works right, if we have an array we get a problem
// if we have sparse keys will get an array back otherwise will get an array
for(var i in result) {
if (i != '______array') {
out += "<li>"+i+" = "+result[i]+"</li>";
}
}
out += "</ul>";
document.getElementById('target').innerHTML = out;
}
}
// setup our remote object from the generated proxy stub
var remoteLiveSearch = new livesearch(callback);
// we could change the queue by overriding the default one, but generally you want to create a new one
// set our remote object to use the ordered queue
remoteLiveSearch.dispatcher.queue = 'ordered';
HTML_AJAX.queues['ordered'] = new HTML_AJAX_Queue_Ordered();
// what to call on onkeyup, you might want some logic here to not search on empty strings or to do something else in those cases
function searchRequest(searchBox) {
remoteLiveSearch.search(searchBox.value);
}
</script>
<p>This is a really basic LiveSearch example, type in the box below to find a fruit</p>
<p>By deafult server add latency to the request, starting with 5 seconds and reducing 1 second per request</p>
<p>An ordered queue has been used which should make results come back in the order they are sent not the order they are received</p>
<form action="slow_livesearch.php">
<label>Set current latency too: <input name="latency" size=4><input type="submit">
</form>
<hr><br>
Search <input id="search" autocomplete="off" onkeyup="searchRequest(this)">
<div style="white-space: pre; padding: 1em; margin: 1em; width: 600px; height: 300px; border: solid 2px black; overflow: auto;" id="target">Target</div>
</body>
</html>
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
?>

View File

@@ -0,0 +1,56 @@
<?php
/**
* A server that adds artificial latency to requests
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
session_start();
// include the server class
include 'HTML/AJAX/Server.php';
// don't add delays to client library requests
if (!isset($_GET['client']) && !isset($_GET['stub'])) {
if (!isset($_SESSION['sleep']) || $_SESSION['sleep'] == 0) {
$_SESSION['sleep'] = 5;
}
sleep($_SESSION['sleep']--);
}
// extend HTML_AJAX_Server creating our own custom one with init{ClassName} methods for each class it supports calls on
class TestServer extends HTML_AJAX_Server {
// this flag must be set to on init methods
var $initMethods = true;
// init method for the test class, includes needed files an registers it for ajax
function initTest() {
include 'support/test.class.php';
$this->registerClass(new test());
}
// init method for the livesearch class, includes needed files an registers it for ajax
function initLivesearch() {
include 'support/livesearch.class.php';
$this->registerClass(new livesearch());
}
// init method for the testHaa class, includes needed files an registers it for ajax, directly passes in methods to register to specify case in php4
function initTestHaa() {
include 'support/testHaa.class.php';
$this->registerClass(new testHaa(),'testHaa',array('updateClassName'));
}
}
$server = new TestServer();
// handle requests as needed
$server->handleRequest();
?>

View File

@@ -0,0 +1,5 @@
// An example custom javascript library served up by the auto_server
function customLibAlert(msg) {
alert(msg);
}

View File

@@ -0,0 +1,35 @@
<?php
class Interceptor {
/**
* A global interceptor runs all calls not matched by a more specific rule
* This example creates a not logged in error
*/
function intercept($className,$methodName,$params) {
// if you were using php5 you could throw an exception instead of using trigger_error
trigger_error("Not logged in: $className::$methodName");
return $params;
}
/**
* A class level interceptor for the test class
* This examples sets the first parameter to the method name
*/
function test($methodName,$params) {
$params[0] = 'Intercepted: '.$methodName.' - Original: '.$params[0];
return $params;
}
/**
* A method level interceptor for the test::test1 method
* This examples sets the first parameter to boink
*/
function test_test1($params) {
$params[0] = 'Intercepted: boink - Original: '.$params[0];
return $params;
}
}

View File

@@ -0,0 +1,7 @@
<?php
require_once 'HTML/AJAX/Helper.php';
$helper = new HTML_AJAX_Helper();
var_dump($helper->isAJAX());
?>

View File

@@ -0,0 +1,60 @@
<?php
/**
* Simple test class for doing fake livesearch
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
class livesearch {
/**
* Items to search against
*/
var $livesearch = array(
'Orange',
'Apple',
'Pear',
'Banana',
'Blueberry',
'Fig',
'Apricot',
'Cherry',
'Peach',
'Plum',
'Nectarine',
'Boysenberry',
'Cranberry',
'Blackberry',
'Clementine',
'Grapefruit',
'Lemon',
'Lime',
'Tangerine'
);
/**
* Perform a search
*
* @return array
*/
function search($input="") {
$ret = array();
if(empty($input)) {
return $ret;
}
if (isset($_SESSION['sleep'])) {
$ret['Latency Added'] = $_SESSION['sleep'];
}
foreach($this->livesearch as $key => $value) {
if (stristr($value,$input)) {
$ret[$key] = $value;
}
}
return $ret;
}
}
?>

View File

@@ -0,0 +1,3 @@
<?php
var_dump($_POST);
?>

View File

@@ -0,0 +1,68 @@
<?php
/**
* Test class used in other examples
* Constructors and private methods marked with _ are never exported in proxies to JavaScript
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
class test {
function test() {
}
function _private() {
}
function echo_string($string) {
return "From PHP: ".$string;
}
function echo_strings($strings) {
return $strings;
}
function slow_echo_string($string) {
sleep(2);
return "From PHP: ".$string;
}
function error_test($string) {
trigger_error($string);
}
function multiarg() {
$args = func_get_args();
return "passed in ".count($args)." args ".var_export($args, TRUE);
}
function cookies() {
return $_COOKIE;
}
function echo_data($data) {
return array('From PHP:'=>$data);
}
function dump($data) {
return print_r($data, true);
}
function unicode_data() {
$returnData = array('word' => mb_convert_encoding('Français','UTF-8'), 'suggestion' => array(mb_convert_encoding('Français','UTF-8'), mb_convert_encoding('caractères','UTF-8')));
return $returnData;
}
function test1($in) {
return $in;
}
function test2($in) {
return $in;
}
function test3($in) {
return $in;
}
}
if (isset($_GET['TEST_CLASS'])) {
$t = new test();
var_dump($t->echo_string('test string'));
var_dump($t->slow_echo_string('test string'));
var_dump($t->error_test('test string'));
var_dump($t->multiarg('arg1','arg2','arg3'));
}
?>

View File

@@ -0,0 +1,18 @@
<?php
/**
* Test class used in other examples
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
class test2 {
function test($in) {
return $in;
}
}
?>

View File

@@ -0,0 +1,37 @@
<?php
/**
* Require the action class
*/
require_once 'HTML/AJAX/Action.php';
class testHaa {
function updateClassName() {
$response = new HTML_AJAX_Action();
$response->assignAttr('test','className','test');
return $response;
}
function greenText($id) {
$response = new HTML_AJAX_Action();
$response->assignAttr($id,'style','color: green');
return $response;
}
function highlight($id) {
$response = new HTML_AJAX_Action();
$response->assignAttr($id,'style','background-color: yellow');
return $response;
}
function duplicate($id,$dest) {
// there really should be an action method to do this
$response = new HTML_AJAX_Action();
$response->insertScript("
var newNode = document.getElementById('$id').cloneNode(true);
newNode.id = 'newNode';
document.getElementById('$dest').appendChild(newNode);");
return $response;
}
}

View File

@@ -0,0 +1,119 @@
<?php
/**
* Test class used in xml examples - notice we have a dom(php5) and a domxml(php4) version
*
* @category HTML
* @package AJAX
* @author Elizabeth Smith <auroraeosrose@gmail.com>
* @copyright 2005-2006 Elizabeth Smith
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
class TestXml {
function createHealthy()
{
if(extension_loaded('Dom'))
{
$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('root');
$root = $dom->appendChild($root);
$element = $dom->createElement('item');
$element = $root->appendChild($element);
$element->setAttribute('type', 'fruit');
$element->appendChild($dom->createTextNode('peach'));
$element = $dom->createElement('item');
$element = $root->appendChild($element);
$element->setAttribute('type', 'fruit');
$element->appendChild($dom->createTextNode('plum'));
$element = $dom->createElement('item');
$element = $root->appendChild($element);
$element->setAttribute('type', 'vegetable');
$element->appendChild($dom->createTextNode('carrot'));
return $dom;
}
elseif (extension_loaded('Domxml'))
{
$dom = domxml_new_doc('1.0');
$element = $dom->create_element('root');
$root = $dom->append_child($element);
$element = $dom->create_element('item');
$element->set_attribute('type', 'fruit');
$element->set_content('peach');
$root->append_child($element);
$element = $dom->create_element('item');
$element->set_attribute('type', 'fruit');
$element->set_content('plum');
$root->append_child($element);
$element = $dom->create_element('item');
$element->set_attribute('type', 'vegetable');
$element->set_content('carrot');
$root->append_child($element);
return $dom;
}
else {
return 'No Dom Support';
}
}
function createJunk()
{
if(extension_loaded('Dom'))
{
$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('root');
$root = $dom->appendChild($root);
$element = $dom->createElement('item');
$element = $root->appendChild($element);
$element->setAttribute('type', 'drink');
$element->appendChild($dom->createTextNode('coke'));
$element = $dom->createElement('item');
$element = $root->appendChild($element);
$element->setAttribute('type', 'drink');
$element->appendChild($dom->createTextNode('beer'));
$element = $dom->createElement('item');
$element = $root->appendChild($element);
$element->setAttribute('type', 'dessert');
$element->appendChild($dom->createTextNode('pie'));
return $dom;
}
else if(extension_loaded('Domxml'))
{
$dom = domxml_new_doc('1.0');
$element = $dom->create_element('root');
$root = $dom->append_child($element);
$element = $dom->create_element('item');
$element->set_attribute('type', 'fruit');
$element->set_content('peach');
$root->append_child($element);
$element = $dom->create_element('item');
$element->set_attribute('type', 'fruit');
$element->set_content('plum');
$root->append_child($element);
$element = $dom->create_element('item');
$element->set_attribute('type', 'vegetable');
$element->set_content('carrot');
$root->append_child($element);
return $dom;
}
else {
return 'No Dom Support';
}
}
function writeDoc($dom) {
if(extension_loaded('Dom'))
{
// save implementation is broken in dom right now
file_put_contents('test.xml', $dom->saveXML());
}
else if(extension_loaded('Domxml'))
{
$doc->dump_file(realpath('test.xml'),false,true);
}
else {
return 'No Dom Support';
}
}
}
?>

View File

@@ -0,0 +1,49 @@
<html>
<head>
<title>Behavior Speed Test</title>
<script type="text/javascript" src="../server.php?client=util,main,alias,behavior"></script>
<script type="text/javascript">
Behavior.debug = 'debug';
Behavior.register('.one',function(element) {
element.style.color = 'red';
}
);
Behavior.register('.two',function(element) {
element.style.color = 'blue';
}
);
Behavior.register('.three',function(element) {
element.style.color = 'green';
}
);
Behavior.register('.four',function(element) {
element.style.color = 'orange';
}
);
Behavior.register('.five',function(element) {
element.style.color = 'purple';
}
);
</script>
</head>
<body>
<p>This page is used to test the speed of HTML_AJAX's JavaScript Behavior support.</p>
<pre id="debug">
</pre>
<?php
$classes = array('one','two','three','four','five');
for($i = 0; $i < 100; $i++) {
$class = $classes[array_rand($classes)];
echo "<div class='$class' id='el$i'>$class";
for($b = 0; $b < 50; $b++) {
$c = $classes[array_rand($classes)];
echo "<span class='$c' id='el$i$b'>$c</span>";
}
echo "</div>\n";
}
?>
</body>
</html>

View File

@@ -0,0 +1,16 @@
<?php
/**
* Duplicate JS files are automatically removed by HTML_AJAX_Server
*
* This is a test for that functionality
*/
?>
<html>
<head>
<title>Duplicate JS library Test</title>
<script src="../server.php?client=Queue,orderedQueue,priorityqueue"></script>
</head>
<body>
<p>Nothing to see here, view: <a href="../server.php?client=Queue,orderedQueue,priorityqueue">../server.php?client=Queue,orderedQueue,priorityQueue</a> to test</p>
</body>
</html>

View File

@@ -0,0 +1,51 @@
<?php
/**
* HTML_AJAX_Util.getElements*() examples
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn josh@bluga.net
* @copyright 2006 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
?>
<html>
<head>
<title>HTML_AJAX_Util.getElements* examples</title>
<script type="text/javascript" src="../server.php?client=util"></script>
</head>
<body>
<div id="t">
<div id="test_one" class="test">Blah</div>
<div id="test_two" class="yellow">blah 2</div>
<div id="three" class="test">Blah 3</div>
</div>
<h3>Test HTML</h3>
<pre id="target0"></pre>
<h3>getElementsByClassName</h3>
<div id="target1"></div>
<h3>getElementsById</h3>
<div id="target2"></div>
<script type="text/javascript">
document.getElementById('target0').innerHTML = HTML_AJAX_Util.htmlEscape(document.getElementById('t').innerHTML);
var els = HTML_AJAX_Util.getElementsByClassName('test');
var t = document.getElementById('target1');
for(var i = 0; i < els.length; i++) {
t.innerHTML += "Found: "+els[i].innerHTML+"<br>";
}
var els = HTML_AJAX_Util.getElementsById('test');
var t = document.getElementById('target2');
for(var i = 0; i < els.length; i++) {
t.innerHTML += "Found: "+els[i].innerHTML+"<br>";
}
</script>
</body>
</html>

View File

@@ -0,0 +1,90 @@
<?php
/**
* HTML_AJAX_Util.varDump() examples
*
* @category HTML
* @package AJAX
* @author Arpad Ray <arpad@php.net>
* @copyright 2005 Arpad Ray
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
?>
<html>
<head>
<script type="text/javascript" src="../server.php?client=util"></script>
<script type="text/javascript">
function foo() {
this.bar = "baz";
this.bat = 5;
}
var obj = new foo();
var a = [
null,
true,
13,
1.337,
'foo',
[1, 2, 3],
[1, [1, 2, 3], 3],
obj
];
function dotest() {
var foo = document.getElementById("foo");
for (ak in a) {
foo.innerHTML += "<pre>" + HTML_AJAX_Util.varDump(a[ak], 1) + "</pre><br>";
}
}
</script></head><body onload="dotest()">
<hr>
PHP:
<hr>
<div>
<?php
class foo {
var $bar = 'baz';
var $bat = 5;
}
$obj = new foo;
$a = array(
null,
true,
13,
1.337,
'foo',
array(1, 2, 3),
array(1, array(1, 2, 3), 3),
$obj
);
foreach ($a as $v) {
echo "<pre>";
var_dump($v);
echo "</pre>";
}
?>
</div>
<hr>
Javascript:
<hr>
<div id="foo">
</div>
<hr>
Source:
<hr>
<div>
<?php show_source(__FILE__); ?>
</div>
</body>
</html>

View File

@@ -0,0 +1,106 @@
<script type="text/javascript" src="../server.php?client=phpSerializer,util"></script>
<?php
$examples = array(
'$foo = null;',
'$foo = true;',
'$foo = "foobar";',
'$foo = 337;',
'$foo = 99.99;',
'$foo = array("a" => 1, "b" => 2, 3);',
'$foo = array(1,2,array(1,2,3));',
'class Foo { var $foo; var $bar; }'
. '$foo = new Foo; $foo->foo = "hello"; $foo->bar = array("world","universe");'
);
echo '<h1><a name="pos">Positives</a> | <a href="#neg">Negatives</a></h1>';
$c = count($examples);
for ($i = 0; $i < $c; $i++) {
echo "<strong>PHP Code:</strong>\n<pre>$examples[$i]</pre>\n<strong>PHP value:</strong><pre>\n";
eval($examples[$i]);
var_dump($foo);
$sfoo = serialize($foo);
echo "</pre>\n<strong>Serialized in PHP:</strong>\n<pre>", $sfoo, "</pre>\n",
"<strong>Unserialized in JS:</strong>\n<pre>\n",
'<script type="text/javascript">',
'var jsr = new HTML_AJAX_Serialize_PHP();',
'var sfoo = unescape("', urlencode($sfoo), '"); var usfoo = jsr.unserialize(sfoo); if (jsr.error) {',
'document.write("Error: " + jsr.getError() + "\n"); } document.write(HTML_AJAX_Util.varDump(usfoo) + ',
'"</pre>\n<strong>Serialized in JS:</strong>\n<pre>" + jsr.serialize(usfoo));', "</script>\n</pre>\n<hr />\n\n";
}
$bad_examples = array(
'x',
'x:1',
'N',
'Nx',
'b:f;',
'b:1',
'i:foo;',
'i:1',
'd:foo;',
'd:1.1.1;',
'd:1.1',
's:6:"foo";',
's:6:"foofoo"',
's:1:"foo";',
's:0:""',
'a:3:{s:1:"aa";i:1;s:1:"b";i:2;i:0;i:3;}',
'a:4:{s:1:"a";i:1;s:1:"b";i:2;i:0;i:3;',
'a:3:{i:1;s:1:"b";i:2;i:0;i:3;}',
'a:3:{}',
'O:3:"Fooo":2:{s:3:"foo";s:5:"hello";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}',
'O:3:"Foo":3:{s:3:"foo";s:5:"hello";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}',
'O:3:"Foo":2:{s:5:"hello";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}',
'O:3:"Foo":2:{s:3:"foo";s:5:"hello";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}',
'O:3:"Foo":2:{s:3:"foo";s:5:"hello";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe"}}'
);
echo '<h1><a href="#pos">Positives</a> | <a name="neg">Negatives</a></h1>';
foreach ($bad_examples as $sfoo) {
echo "</pre>\n<strong>Invalidly serialized:</strong>\n<pre>", $sfoo, "</pre>\n",
"<strong>Unserialized in JS:</strong>\n<pre>\n",
'<script type="text/javascript">',
'var sfoo = unescape("', urlencode($sfoo), '"); var usfoo = jsr.unserialize(sfoo); if (jsr.error) {',
'document.write("Error: " + jsr.getError() + "\n"); } document.write(HTML_AJAX_Util.varDump(usfoo));',
"</script>\n</pre>\n<hr />\n\n";
}
$good_objects = array(
'O:3:"Foo":2:{s:3:"foo";s:5:"hello";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}',
'O:3:"Foo":2:{s:3:"foo";s:87:"O:3:"Bar":2:{s:3:"foo";s:5:"hello";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}',
'O:3:"Foo":2:{s:3:"foo";s:90:"hi"O:3:"Bar":2:{s:3:"foo";s:5:"hello";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}'
);
$bad_objects = array(
'O:6:"stdClass":2:{s:3:"foo";s:5:"hello";s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}',
'O:3:"Foo":2:{s:3:"foo";O:8:"stdClass":1:{s:3:"bar";s:2:"hi";}s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}',
'O:3:"Foo":2:{s:6:"hi"foo";O:8:"stdClass":1:{s:3:"bar";s:2:"hi";}s:3:"bar";a:2:{i:0;s:5:"world";i:1;s:8:"universe";}}'
);
include('HTML/AJAX/Serializer/PHP.php');
$sr = new HTML_AJAX_Serializer_PHP;
$allowedClasses = array('Foo');
echo '<h1><a name="opos">Object Positives</a> | <a href="#oneg">Object Negatives</a></h1>';
foreach ($good_objects as $sfoo) {
echo "</pre>\n<strong>Serialized in PHP:</strong>\n<pre>", $sfoo, "</pre>\n",
"<strong>Class Names</strong><pre>\n", implode(', ', $sr->_getSerializedClassNames($sfoo)),
"</pre><strong>Unserialized in PHP:</strong>\n<pre>\n";
var_dump($sr->unserialize($sfoo, $allowedClasses));
echo "</pre>\n<hr />\n\n";
}
echo '<h1><a href="#opos">Object Positives</a> | <a name="oneg">Object Negatives</a></h1>';
foreach ($bad_objects as $sfoo) {
echo "</pre>\n<strong>Serialized in PHP:</strong>\n<pre>", $sfoo, "</pre>\n",
"<strong>Class Names</strong><pre>\n", implode(', ', $sr->_getSerializedClassNames($sfoo)),
"</pre><strong>Unserialized in PHP:</strong>\n<pre>\n";
var_dump($sr->unserialize($sfoo, $allowedClasses));
echo "</pre>\n<hr />\n\n";
}
?>

View File

@@ -0,0 +1,73 @@
<?php
/**
* Test cases for the UrlSerializer
*/
?>
<script type="text/javascript" src="../server.php?client=UrlSerializer,util"></script>
<script type="text/javascript">
</script>
<?php
$examples = array(
'$foo = null;',
'$foo = true;',
'$foo = "foobar";',
'$foo = 337;',
'$foo = 99.99;',
'$foo = array("a" => 1, "b" => 2, 3);',
'$foo = array(1,2,array(1,2,3));',
'class Foo { var $foo; var $bar; }'
. '$foo = new Foo; $foo->foo = "hello"; $foo->bar = array("world","universe");'
);
require_once 'HTML/AJAX/Serializer/Urlencoded.php';
$sr = new HTML_AJAX_Serializer_Urlencoded;
echo '<h1><a name="pos">Positives</a> | <a href="#neg">Negatives</a></h1>';
$c = count($examples);
for ($i = 0; $i < $c; $i++) {
echo "<strong>PHP Code:</strong>\n<pre>$examples[$i]</pre>\n<strong>PHP value:</strong><pre>\n";
eval($examples[$i]);
var_dump($foo);
$sfoo = $sr->serialize($foo);
echo "</pre>\n<strong>Unserialized in PHP:</strong>\n<pre>";
var_dump($sr->unserialize($sfoo));
echo "</pre>\n<strong>Unserialized in JS:</strong>\n<pre>\n",
'<script type="text/javascript">',
'var jsr = new HTML_AJAX_Serialize_Urlencoded();',
'var sfoo = unescape("', urlencode($sfoo), '"); var usfoo = jsr.unserialize(sfoo); if (jsr.error) {',
'document.write("Error: " + jsr.getError() + "\n"); } document.write(HTML_AJAX_Util.varDump(usfoo) + ',
'"</pre>\n<strong>Serialized in PHP:</strong>\n<pre>', $sfoo, '</pre>\n',
'\n<strong>Serialized in JS:</strong>\n<pre>" + jsr.serialize(usfoo));',
"\n</script>\n</pre>\n<hr />\n\n";
}
$bad_examples = array(
'x',
'x-1',
'x=1x=2',
'x=1&',
'x[=]1',
'[]x=1',
'_HTML_AJAX]]=1',
'_HTML_AJAX[[=1',
'_HTML_AJAX][=1',
'_HTML_AJAX[=]1',
'_HTML_AJAX[=1]',
'_HTML_AJAX[0]=1&_HTML_AJAX]]=1',
'_HTML_AJAX[0[1]]=1',
'_HTML_AJAX[0[1]=1'
);
echo '<h1><a href="#pos">Positives</a> | <a name="neg">Negatives</a></h1>';
foreach ($bad_examples as $sfoo) {
echo "</pre>\n<strong>Invalidly serialized:</strong>\n<pre>", $sfoo, "</pre>\n",
"<strong>Unserialized in JS:</strong>\n<pre>\n",
'<script type="text/javascript">',
'var sfoo = unescape("', urlencode($sfoo), '"); var usfoo = jsr.unserialize(sfoo); if (jsr.error) {',
'document.write("Error: " + jsr.getError() + "\n"); } document.write(HTML_AJAX_Util.varDump(usfoo));',
"</script>\n</pre>\n<hr />\n\n";
}
?>

View File

@@ -0,0 +1 @@
alert('Loaded setInnerHTML.js');

View File

@@ -0,0 +1,132 @@
<?php
/**
* HTML_AJAX_Util.setInnerHTML tests
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2006 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
?>
<html>
<head>
<style type="text/css">
div {
padding: 1em;
margin: 1em;
border: solid 1px black;
}
pre {
padding: 1em;
border: dotted 1px black;
}
</style>
<script type="text/javascript" src="../server.php?client=util"></script>
<script type="text/javascript">
function test(compareto,input,mode) {
if (compareto == true) {
compareto = input;
}
document.getElementById('input').innerHTML = HTML_AJAX_Util.htmlEscape(input);
HTML_AJAX_Util.setInnerHTML('target',input,mode);
document.getElementById('source').innerHTML = HTML_AJAX_Util.htmlEscape(document.getElementById('target').innerHTML);
document.getElementById('status').innerHTML = 'Test Successful';
document.getElementById('status').style.color = 'green';
if (compareto == false) {
document.getElementById('status').innerHTML = 'Nothing to compare against';
document.getElementById('status').style.color = 'yellow';
return;
}
if (compareto != document.getElementById('target').innerHTML) {
document.getElementById('status').innerHTML = 'Test Failed';
document.getElementById('status').style.color = 'red';
}
}
function test1() {
test(true,'<script type="text/javascript">alert("hello world");</'+'script>');
}
function test2() {
test(true,'<div id="blah">Blah Blah</div><script type="text/javascript">document.getElementById("target").style.color = "blue";</'+'script><div>blah blah</div>');
}
function test3() {
test(true,'<script type="text/javascript">function blah() { document.getElementById("target").style.color = "blue"; }</'+'script><div>Blah Blah</div><script type="text/javascript">blah();</'+'script><div>blah blah</div>');
}
function test4() {
test(true,'<script type="text/javascript">function blah() { document.getElementById("target").style.color = "blue"; }</'+'script>'+"\n"+
'<form><fieldset><legend>Fieldset</legend>'+"\n"+
'<div>Blah Blah</div>'+"\n"+
'<script type="text/javascript">blah();</'+'script>'+"\n"+
'<div>blah blah</div></fieldset></form>');
}
function test5() {
test(false,'<div>start</div>');
test('<div>Add</div><div>start</div>','<div>Add</div>','prepend');
}
function test6() {
test(false,'<div>start</div>');
test('<div>start</div><div>Add</div>','<div>Add</div>','append');
}
function test7() {
test(false,'<img src="http://phpdoc.org/images/logo-trans.png" onload="this.style.border = \'solid 10px orange\'">');
}
function test8() {
test(false,'<script type="text/javascript">document.write("Hello World")</'+'script>');
}
function test9() {
test(false,'<script type="text/javascript" src="setInnerHTML.js"></'+'script>');
}
function test10() {
test(false,'<script type="text/javascript">function blah() { document.getElementById("target").style.color = "blue"; }</'+'script>Test');
blah();
}
function test11() {
HTML_AJAX_Util.setInnerHTML('target','<p>blah</p>');
HTML_AJAX_Util.setInnerHTML('target','<p>blah</a>');
}
function test12() {
test(false,'<div id="test12">Blah</div><script type="text/javascript">document.getElementById("test12").style.color = "orange";</s'+'cript>');
}
function test13() {
test(false, '<script type="text/javascript">\n<!--\n alert("hello world from comments!");\n//-->\n</' + 'script>');
}
function test14() {
test(false, '<script type="text/javascript">\n<![CDATA[\n alert("hello world from cdata comments!");\n]]>\n</' + 'script>');
}
</script>
</head>
<body>
<ol>
<li><a href="javascript:test1()">Basic Test just a script block</a></li>
<li><a href="javascript:test2()">Script block with content before and after</a></li>
<li><a href="javascript:test3()">Script content Script content</a></li>
<li><a href="javascript:test4()">Script form content Script content /form</a></li>
<li><a href="javascript:test5()">Prepend</a></li>
<li><a href="javascript:test6()">Append</a></li>
<li><a href="javascript:test7()">onload</a></li>
<li><a href="javascript:test8()">document.write</a></li>
<li><a href="javascript:test9()">load an external js file</a></li>
<li><a href="javascript:test10()">Create a function and call it in the parent scope</a></li>
<li><a href="javascript:test11()">Replace/Replace make sure default mode is detected properly</a></li>
<li><a href="javascript:test12()">Use an element adding in this set latter in the process</a></li>
<li><a href="javascript:test13()">Script inside comment</a></li>
<li><a href="javascript:test14()">Script inside cdata comment</a></li>
</ol>
<div id="status"></div>
<h3>Input String</h3>
<pre id="input">
</pre>
<h3>HTML Source Output</h3>
<pre id="source">
</pre>
<h3>Normal Output</h3>
<div id="target">
</div>

View File

@@ -0,0 +1,88 @@
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
How to use behavior.js
</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="../server.php?client=behavior" type="text/javascript"></script>
<script type="text/javascript">
Behavior.register(
".alert",
function(element) {
element.onclick = function(){
alert('I alert on click');
}
}
);
Behavior.register(
".annoy",
function(element) {
element.onmouseout = function(){
alert('I alert on mouseout, very annoying');
}
}
);
Behavior.register(
".red",
function(element) {
element.onmouseover = function(){
element.style.backgroundColor = 'red';
}
}
);
</script>
</head>
<body>
<p>
This file requires two javascript files to work properly. They are behavior.js and css-Query-p.js and can be found in the js/behaviors folder.
The script allows you to apply behaviors to a css class, so you don't pollute your html with a ton of
inline javascript. The example below uses the following script tag to apply the behaviors.
you can also link external javascript files to apply behaviors as well.
</p>
<pre>
Behavior.register(
".alert",
function(element) {
element.onclick = function(){
alert('I alert on click');
}
}
);
Behavior.register(
".annoy",
function(element) {
element.onmouseout = function(){
alert('I alert on mouseout, very annoying');
}
}
);
Behavior.register(
".red",
function(element) {
element.onmouseover = function(){
element.style.backgroundColor = 'red';
}
}
);
</pre>
<div style="border: 1px solid black; width: 50%; margin: 5em">
<div class="alert">
I am a div that alerts when you click on me - notice I just have class="alert" to make it work :)
</div>
<div class="annoy">
I am a div that alerts when you mouseout me - class="annoy" makes it work
</div>
<div class=" alert red">
I am a div that alerts when you click on me and the background turns red on mouseover - class="alert red"
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,83 @@
<?php
/**
* Priority queue test.
*
* Makes 10 calls at one priority, then 10 calls at a higher priority.
*
* @category HTML
* @package AJAX
* @author Arpad Ray <arpad@php.net>
* @copyright 2005 Arpad Ray
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
include 'HTML/AJAX.php';
include '../support/test.class.php';
$ajax = new HTML_AJAX();
$ajax->serializer = "Null";
$ajax->unserializer = "Null";
$ajax->registerClass(new test());
if ($ajax->handleRequest()) {
die();
}
?><html>
<head>
<script type='text/javascript' src="../server.php?client=all&amp;stub=all"></script>
<script type="text/javascript">
HTML_AJAX.queues['priority'] = new HTML_AJAX_Queue_Priority_Simple(40);
var t = new test({echo_string: function(result){ endCall(result); }});
var time1;
var count = 0;
function priorityTest() {
document.getElementById('target').innerHTML += "<br><br>";
count = 0;
for (var i = 0; i < 10; i++) {
runLow(i);
}
for (var i = 0; i < 10; i++) {
runHigh(i);
}
total = 0;
}
function runLow(i) {
startCall();
t.dispatcher.queue = 'priority';
t.dispatcher.priority = 10;
return t.echo_string('Not urgent, number ' + i + ' ');
}
function runHigh(i) {
startCall();
t.dispatcher.queue = 'priority';
t.dispatcher.priority = 0;
return t.echo_string('Urgent, number ' + i + ' ');
}
function startCall() {
time1 = new Date();
}
function endCall(name) {
var time = 0;
var time2 = new Date();
time = time2.getTime() - time1.getTime();
document.getElementById('target').innerHTML += name + "time: " + time + "<br>";
if (++count == 20) {
document.getElementById('target').innerHTML += "Done<br>";
}
}
</script>
</head>
<body>
<a href="javascript:priorityTest()">Start Priority Test</a>
<div id="target">
</div>
</body>
</html>

View File

@@ -0,0 +1,91 @@
<?php
/**
* Simple speed test using the null serializer, possibly useful in comparing overhead when tested on local host
*
*
* @category HTML
* @package AJAX
* @author Joshua Eichorn <josh@bluga.net>
* @copyright 2005 Joshua Eichorn
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
include 'HTML/AJAX.php';
include '../support/test.class.php';
$ajax = new HTML_AJAX();
$ajax->serializer = "Null";
$ajax->unserializer = "Null";
$ajax->registerClass(new test());
if ($ajax->handleRequest()) {
die();
}
?><html>
<head>
<script type='text/javascript' src="../server.php?client=all&stub=all"></script>
</head>
<body>
<script type="text/javascript">
var t = new test();
var t2 = new test({echo_string: function(){ endCall('Async Echo'); totalA(); }});
var time1;
var total = 0;
var count = 0;
function speedTest() {
document.getElementById('target').innerHTML += "10 Sync Calls<br>";
for(var i = 0; i < 10; i++) {
startCall();
t.echo_string('Test');
endCall('Sync Echo');
}
document.getElementById('target').innerHTML += "Total: "+total+"<br><br><br>";
total = 0;
document.getElementById('target').innerHTML += "10 Async Calls<br>";
count = 0;
for(var i = 0; i < 10; i++) {
setTimeout("runAsync();",500*i);
}
total = 0;
}
function totalA() {
count++;
if (count == 10) {
document.getElementById('target').innerHTML += "Total: "+total+"<br>";
}
}
function runAsync() {
startCall();
t2.echo_string('Test');
}
function startCall() {
time1 = new Date();
}
function endCall(name) {
var time = 0;
var time2 = new Date();
time = time2.getTime() - time1.getTime();
total += time;
document.getElementById('target').innerHTML += name+":"+time+"<br>";
}
</script>
<a href="javascript:speedTest()">Start Speed Test</a>
<div id="target">
</div>
</body>
</html>

View File

@@ -0,0 +1,132 @@
<?php
/**
* Example of Using HTML_AJAX in proxy operation
*
* All AJAX calls are handled by the xmlserver.php
*
* The only needed interaction is creation of a new object from the proxy defintion, all AJAX calls happen transparently from there
*
* If you want to perform async calls a callback object must be passed to the constructor of the object
*
* @category HTML
* @package AJAX
* @author Elizabeth Smith <auroraeosrose@gmail.com>
* @copyright 2006 Elizabeth Smith
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version Release: 0.5.2
* @link http://pear.php.net/package/HTML_AJAX
*/
?><html>
<head>
<script type='text/javascript' src="xmlserver.php?client=all"></script>
<script type='text/javascript' src="xmlserver.php?stub=testxml"></script>
<script type='text/javascript'>
// function to display xml received from server
function showItems(xml)
{
var list=xml.getElementsByTagName('item');
document.getElementById('target').innerHTML = '<p>My Fridge</p>';
for (var i=0;i<list.length;i++)
{
var node = list[i];
document.getElementById('target').innerHTML += '<p>' + node.firstChild.nodeValue
+ ' is a ' + node.getAttribute('type') + '</p>';
}
}
// function to display xml created here
function showMessage(xml)
{
var list=xml.getElementsByTagName('tag');
document.getElementById('target').innerHTML = '';
for (var i=0;i<list.length;i++)
{
var node = list[i];
document.getElementById('target').innerHTML += '<p>' + node.firstChild.nodeValue + '</p>';
}
}
// definition of the callback javascript class, used to handle async requests
function callback() {}
callback.prototype = {
createJunk: function(result) {
showItems(result);
},
writeDoc: function(result) {
dom = HTML_AJAX.grab('test.xml');
showMessage(dom);
}
}
// function used to clear out the target div
function clearTarget() {
document.getElementById('target').innerHTML = 'clear';
}
//create xml document to send back to server
var xmlhello = '<' + '?xml version="1.0"?><root><tag>Hello</tag></root>';
xmlhello = new DOMParser().parseFromString(xmlhello, 'text/xml');
var xmlgoodbye = '<' + '?xml version="1.0"?><root><tag>Goodbye</tag></root>';
xmlgoodbye = new DOMParser().parseFromString(xmlgoodbye, 'text/xml');
</script>
</head>
<body>
<script type="text/javascript">
// create a proxy in sync mode
var syncProxy = new TestXml();
// create a proxy in async mode
var asyncProxy = new TestXml(new callback());
// run a sync call and set its results to the target div
function syncCall() {
dom = syncProxy.createHealthy();
showItems(dom);
}
function syncSend(xml) {
syncProxy.writeDoc(xml);
dom = HTML_AJAX.grab('test.xml');
showMessage(dom);
}
// run a sync call, callback class will handle its results
function asyncCall() {
asyncProxy.createJunk();
}
// run a sync call, callback class will handle its results
function asyncSend(xml) {
asyncProxy.writeDoc(xml);
}
</script>
<p>HTML_AJAX XML functionality needs the Dom extensions in PHP5 or the DOMXML extension in PHP4.<br>
It looks like you have:<br>
<?php
if (extension_loaded('Dom')) {
echo 'The Dom extension';
}
else if (extension_loaded('Domxml')) {
echo 'The Domxml extension';
}
else {
echo 'No XML DOM support, so you can expect these examples to fail';
}
?>
</p>
<ul>
<li><a href="javascript:clearTarget()">Clear Target</a></li>
<li><a href="javascript:syncCall()">Retrieve XmlDom Sync</a></li>
<li><a href="javascript:asyncCall();">Retrieve XmlDom Async</a></li>
<li><a href="javascript:syncSend(xmlhello);">Send XmlDom Sync</a></li>
<li><a href="javascript:asyncSend(xmlgoodbye);">Send XmlDom Async</a></li>
</ul>
<div style="white-space: pre; padding: 1em; margin: 1em; width: 600px; height: 300px; border: solid 2px black; overflow: auto;" id="target">Target</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,12 @@
<?php
include 'HTML/AJAX/Server.php';
include 'support/xml.class.php';
$server = new HTML_AJAX_Server();
// register an instance of the class were registering
$xml =& new TestXml();
$server->registerClass($xml,'TestXml',array('createHealthy','createJunk','writeDoc'));
$server->setSerializer('XML');
$server->handleRequest();
?>