AJAX Handlers are very similar to
Event Handlers for Code Behind Pages.
AJAX Handlers provide a way for you to trigger an event or perform actions without the need of a page refresh. When an AJAX (Asyncronous Javascript and XML) request is sent to your page, it can be directed an AJAX Handler. This method will perform any actions that you need and directly echo its result. Once the AJAX Handler is finished, the TextSide Engine script immediately exits.
To create an AJAX Handler, simply name a method ajax
Name() inside your page class. For example: function ajaxGetTime(). Whenever the page is loaded with the variable $ajax set to "GetTime" in $_GET or $_POST, the AJAX handler would be invoked.
In order to use AJAX Handlers you will need to create an AJAX Request to your page via some Javascript. The TextSide Engine come bundled with the
Prototype Framework, which includes
many AJAX features. It also comes bundled with a few Javascript functions (covered below) that let you easily call Ajax Handlers from within your HTML.
Below is a short example of using AJAX Handlers. Here I've created a simple AJAX example that will obtain the current time whenever the "Get Time" button is pressed.
Directory Structure:
================================
AjaxTest.php
|--bin/
|--templates/
| |--AjaxTest.tmpl.php
|--js/
|--AjaxTest.js
AjaxTest.php (CodeBehind Page)
================================
<?php
class pageAjaxTest extends page {
var $layout = "Columns1";
/* AREA 2 - Center Page */
function area2(){
$this->title = "AJAX Test Example";
$this->border = 1;
$this->addJavascriptHeader($this->binDirectory."js/AjaxTest.js");
return $this->fetch("AjaxTest.tmpl.php"); }
/* AJAX - Returns the current time */
function ajaxGetTime(){
$today = date("F j, Y, g:i a");
echo("$today");
}
}
?>
AjaxTest.tmpl.php (Template)
================================
<input type="button" value="Get Time" onclick="GetTime()">
<div id="TimeDiv"></div>
AjaxTest.js (Javascript)
================================
function GetTime(){
Util.AjaxRequest("GetTime","",GetTimeCallback);
}
function GetTimeCallback(transport){
$("TimeDiv").innerHTML = transport.responseText;
}
This would be rendered as:
And after the user clicks Get Time:
In the above example an AJAX request was submitted by using the built in Util.AjaxRequest() method. This is a built in Utility method that will automatcally Invoke an Ajax Handler on your current page and returns its result. You can, however, skip this and manually invoke the AJAX request using Prototype's library. Below covers 3 common ways you can make your AJAX requests from Javascript:
This is a built in Utility method provided by TextSide that will submit an Ajax request to your current page. It accepts 4 parameters:
AjaxHandlerName - The name of the Ajax Handler to Trigger. Example: "GetTime"
data - Any extra data to pass to the Ajax Handler. For example: "timezone=5®ion=south"
OnSuccess - A callback method that will be invoked when the ajax request completes
OnFailure - (optional) A callback method that will be invoked if the ajax request fails.
function Util.AjaxRequest(AjaxHandlerName, data, OnSuccess, OnFailure);
An example use:
Util.AjaxRequest("GetTime","",GetTimeCallback);
You can also directly use Prototypes Ajax.Request method to get more control over your AJAX request. For examples on using this class, please see the
Prototype Ajax Tutorial
If you wish to submit your AJAX request to your current page, two helpful global variables are
Site.SiteRoot and
Site.Url. The first gives the absolute url to your sites root (http://www.yoursite.com/") while the second gives the path to your current page relative to the root ("tests/ajaxtest"). Together they can be used to create a request to your current page using Prototype's Ajax.Request method.
Here's an example:
new Ajax.Request(Site.SiteRoot + Site.Url, {
method:'post',
parameters:'ajax=GetTime',
onSuccess: GetTimeCallback
});
Note how ajax=GetTime is set in the parameters field to direct the request to your desired AJAX Handler.
Another common case when working with AJAX is submitting an entire form without a page refresh. You can do this with Prototypes .request() method that it automatically appends to form elements accessed in Javascript.
Here's an example:
HTML
==========
<form action="<?=$PHP_SELF?>" method="post" id="MyFormName">
<input type="hidden" name="ajax" value="AjaxHandlerName">
Email: <input type="text" name="email">
<input type="button" value="Signup!" onclick="SubmitMyForm()">
Javascript
==========
function SubmitMyForm()
{
$("MyFormName").request({
onComplete: SubmitMyFormCallback()
});
}
function SubmitMyFormCallback(transport)
{
alert("Form Submitted!");
}
For details on this method, please see
The Prototype Documentation.
Often you'll want your AJAX Handlers to return some information to the page that invoked them. A handy way to do this is using
JSON. JSON is a lightweight data interchange format that is often used to send information back to Javscript, as it can be easily parsed.
To use JSON in the TextSide Engine, you pass any class, array, or data structure to the method
util::json($object);. This will return a string that you can echo. The Callback Method in your Javascript code can then parse the response into a Javascript object using
Prototypes evalJSON() function.
Heres a short example:
AJAX Handler:
=============
<?php
//...
function ajaxGetUser(){
$username = util::getData("username");
$user = & new user();
$user->loadFromDatabaseByUser($username);
echo util::json($user);
}
//...
?>
Javascript:
=============
function GetUserDetails(name){
Util.AjaxRequest("GetUser","username="+name,GetUserDetailsCallback);
}
function GetUserDetailsCallback(transport){
var user = transport.responseText.evalJSON();
//user object data is now available in Javascript:
alert("FirstName: "+user.firstname);
alert("LastName: "+user.lastname);
}