AJASON

aus Sviki, der freien Wissensdatenbank

Inhaltsverzeichnis [Verbergen]

Abstract

AJASON is a PHP 5 library and JavaScript client for the upcoming Web technology called AJAX. AJAX permits data to be fetched asynchronously without the need for reloading the Web page and thus allows the development of interactive GUI-like Web applications. JSON is a lightweight data interchange format which is used by AJASON to exchange data between server and client.

The key features of AJASON are:

  • Fully object oriented code in PHP 5 and JavaScript
  • Call PHP functions and object methods from JavaScript asynchronously
  • Exchange even complex data types like arrays and objects (precisely object properties) between server and client
  • Use JavaScript callback functions to process server responses
  • Client side error reporting for server side AJASON errors
  • Open source released under the GNU GPL

Requirements

  • Web server with PHP 5 module
  • JavaScript enabled browser, preferably a current Mozilla based browser

Downloads

Version 0.9

  • TAR/BZ2 file (http://prdownloads.sourceforge.net/ajason/AJASON_09.tar.bz2?download)
  • ZIP file (http://prdownloads.sourceforge.net/ajason/AJASON_09.zip?download)

Old releases

Version 0.2

  • TAR/BZ2 file (http://prdownloads.sourceforge.net/ajason/AJASON_02.tar.bz2?download)
  • ZIP file (http://prdownloads.sourceforge.net/ajason/AJASON_02.zip?download)

Version 0.1

  • TAR/BZ2 file (http://prdownloads.sourceforge.net/ajason/AJASON_01.tar.bz2?download)

Installation

Extract the archive into a temporary directory. Move the file php/Ajax.php and the directory php/Ajax into the folder of your web project where you store your php libraries, for example htdocs/mywebproject/php. Move the files from javascript into your project specific JavaScript folder (e.g. htdocs/mywebproject/javascript).

Using

The first thing you want to do is to include the JavaScript files ajax.js and json.js in your PHP/HTML document where you are going to use AJASON functionality. It is very important that these scripts are included before any AJASON generated JavaScript code:

<head>
  ...
  <script type="text/javascript" src="javascript/json.js"></script>
  <script type="text/javascript" src="javascript/ajax.js"></script>
  ...
</head>

In your PHP document load the file Ajax.php and create an instance of the Ajax class:

require_once( 'php/Ajax.php' );
$ajax = new Ajax();

Now register all funtions and class/object methods which should be callable from the JavaScript client:

$ajax->registerFunction( 'exampleFunction' );
$ajax->registerMethod( 'ExampleClass', 'exampleMethod' );

If you are going to register a method please note that you can only use static methods or methods of objects which do not require mandatory parameters in the constructor. Constructors will always be called without any parameter! Also keep in mind that the first parameter of registerMethod() is the name of the class not an object.

Now it's time spawn the server object of Ajax and check whether a server request has occured:

$ajaxServer = $ajax->getServer();
if ( $ajaxServer->isRequest() )
{
  echo $ajaxServer->handleRequest();
  exit();
}

If isRequest() returns true a server request is in the process. Let's handle the request and exit the script. If not then there's more to do:

$ajaxClient = $ajax->getClient();

The client is reponsible for creating the JavaScript code. Use the method getJavaScript() to render it at the appropriate position somewhere in your HTML document:

<head>
  ...
  <script type="text/javascript" src="javascript/json.js"></script>
  <script type="text/javascript" src="javascript/ajax.js"></script>
  <script type="text/javascript">
    <?php echo $ajaxClient->getJavaScript(); ?>
  </script>
  ...
</head>

Now let me explain to you how you call a PHP function/method with JavaScript. First have a look at the following code snippet:

<script type="text/javascript">
  function example_cb( response )
  {
    document.getElementById( 'inputExample' ).value = response;
  }
</script>

<form>
  <input type="text" id="inputExample" name="inputExample" />
  <input type="button" id="buttonExample" name="buttonExample"
    onclick="x_ExampleClass.exampleMethod( "hello world!", example_cb );" value="Click me" />
</form>

In the onclick event of the button the method exampleMethod of the class ExampleClass - which we registered previously - is being called. You can pass a variable amount of parameters whereas the last argument can be a function which is then used as a callback function. A callback function will be called as soon as the response from the server has been completely arrived. The response data, which can be a scalar value, an array, an object or any combination of these (e.g. array of objects) is passed to the callback function as the first parameter. You don't need to use a callback function but if you are going to please note that the number of parameters passed to the PHP function/method is n-1 because the callback function won't be passed to the server.

You may have noticed that the name of the class has changed from ExampleClass to x_ExampleClass within JavaScript. This is the default behaviour for all function and class names which are prepended with "x_".

Options

The behaviour of AJASON can be tweaked via several options which are set by the setOption() method of the Ajax class. This method takes two arguments. The first argument is the kind of option, the second argument is the value. Valid options are:

Option Possible values Default value Description
Ajax::MethodOption Ajax::MethodPost, Ajax::MethodGet Ajax::MethodPost Set whether server requests will send data via POST or GET method
Ajax::HandlerOption string none, current PHP script Filename of PHP script which handles server requests
Ajax::DebugOption true, false false Show debug information on client for every AJAX request
Ajax::DisplayErrorsOption true, false true Display critical errors on client
Ajax::PrependOption string "x_" String which will be prepended to every function/class name within JavaScript
Ajax::EncodeOption true, false false Encode return value to UTF-8 before sending to client, see note

Use getOption() to read an option.

$ajax->setOption( Ajax::MethodOption, Ajax::MethodGet );
$ajax->setOption( Ajax::HandlerOption, "server.php" );
$ajax->setOption( Ajax::DebugOption, true );

$currentPrepend = $ajax->getOption( Ajax::PrependOption );

Example applications

  • multiply.php (http://ajason.sven-jacobs.de/examples/multiply/multiply.php)
  • client.php (http://ajason.sven-jacobs.de/examples/client_server/client.php)
  • autocomplete.php (http://ajason.sven-jacobs.de/examples/autocomplete/autocomplete.php)

Security concerns

Thinking about security is good! AJASON only allows to call functions and methods which have been explicitly registered before! But please bear in mind that AJASON does not enforce access privileges of any kind! Every registered function/method can be called by anybody!! Even trying to hide JavaScript AJASON calls for unprivileged users is no good and secure solution at all. Your server side PHP functions/methods must always enforce the rules if required - for example by validating users through a session management.

Character encoding

The third party (http://mike.teczno.com/json.html) PHP JSON library which AJASON is using requires all strings to be encoded in UTF-8. Thus since version 0.9 AJASON provides the option Ajax::EncodeOption. If set to true the return value of the method or function which has been called by the client will be encoded to UTF-8 before passed back to the client. If told to, AJASON takes care of plain strings, strings in arrays and strings in objects. Because the function utf8_encode (http://www.php.net/manual/en/function.utf8-encode.php) is being used for the conversion, strings need to be returned in ISO-8859-1 encoding first.

This leaves us with two options:

  1. Make sure the return value contains strings in ISO-8859-1 and enable Ajax::EncodeOption or
  2. Don't use Ajax::EncodeOption and encode the strings into UTF-8 yourself before returning them

Testing

AJASON 0.9 has been successfully tested with Mozilla Firefox 1.0.6 and Microsoft Internet Explorer 6.0.

Due to a browser bug AJASON does not work with Opera 8.01 (and probably previous versions) when sending data with POST method.

Todo

  • Tests on more browsers
  • Maybe: optional XML response for direct manipulation of DOM objects?
  • Maybe: registering complete classes with all public (static) methods?

Bugs

Report bugs with the SourceForge.net bug tracker (http://sourceforge.net/tracker/?group_id=142769&atid=753557).

Known problems

The JSON JavaScript library (http://www.crockford.com/JSON/js.html) fails to encode associative arrays which means it is not possible to pass associative arrays from client to server at the moment. The other way, from server (PHP) to client (JavaScript), does work though!

Weblinks

  • SourceForge.net project page (http://sourceforge.net/projects/ajason)
  • freshmeat.net project page (http://freshmeat.net/projects/ajason)

Acknowledgment

Thanks to Timo Haberkern who pointed out the UTF-8 problem and contributed some source code.

'Persönliche Werkzeuge