Easy Ajax for the masses with xajax

Saturday Nov 12 2005

A while ago I mentioned I was going to deliver a presentation on PHP and Ajax. The conference on which I delivered it took place last week on November 10. I also promised people I'd translate everything I prepared for the presentation for posting on my weblog. It took some time but here it is! If you're interested in diving into programming your own Ajax functionality with PHP this article might be a nice starter.

Together we'll take a look at the xajax class library for PHP. You'll be surprised how easy it really is to create the nifty stuff you'll find all over the internet lately. I have prepared four documented working examples on how to use xajax in real-world situations. You can study the sourcecode as well as download the whole set to do with it whatever you like. Let's dive into xajax!

Before you proceed: This tutorial is quite old and not based on the latest version of xajax. Because I'm not working with it at the moment I cannot guarantee how up-to-date this tutorial still is. Proceed at your own risk!

Dark Matter Pro: a premium photoblog template.

Affiliate program available

The xajax library

There are many different kinds of ajax libraries and frameworks available for developers these days. Honestly I even think there are too many of them. I've studied the wonderful Prototype.js javascript library and there's the amazing script.aculo.us library for killer visual effects. However these solutions are heavily javascript oriented. Quite some skilled developers only have mediocre javascript skills which can make these libraries rather hard to use in PHP applications.

Luckily I stumbled upon the xajax library which is a purely PHP centered Ajax library. When using there's very, VERY little left to write for us developers which I consider a definite advantage when comparing xajax to various other solutions. I do believe Prototype.js integration could make xajax even better than it already is if implemented without the need for developers to mess with the javascript itself. Luckily this is one of the things planned for future versions of xajax. With all this in mind I believe xajax is a rather solid choice for PHP developers to build their applications on.

Basic principles of xajax

When first starting with xajax there's some things we have to get used to. We can look at xajax based php code as some sort of cyclic process containing server-side and client side events. The real power of xajax lies in the fact that we can call backend PHP functions directly from within the client environment. Functions defined in the backend (the php part) are available in the frontend (the dhtml/javascript part) as well. A very powerful mechanism indeed. The good news for us developers is the fact that 99% of the javascript is generated automatically by xajax.

Let's take a look of what some basic xajax functionality consists of. I have created four different examples that gradually become a little bit more complex. However the same principles apply to all examples. Let's take a look at these base principles:

Step 1: include the xajax class library

require_once("xajax.inc.php");

A no-brainer of course. We always have to include the xajax class library.

Step 2: A server-side xajax function

function makeBold($p_sArg)  {
  $sOut = '<b>'.$p_sArg.'</b>';
  $objResponse is new xajaxResponse();
  $objResponse->addAssign('my_element', 'innerHTML', $sOut); 
  return $objResponse->getXML();
  }

The above function takes a string argument $p_sArg and returns it within a html <b> tag. First we instantiate an xajaxResponse object which will handle the response to the client. Secondly, we assign a HTML element to update to the xajaxResponse object. The xajaxResponse->addAssign() method takes three arguments:

  1. the name of an HTML element in our page
  2. The property of the element we want to change client-side
  3. The stuff we want to send to the client
Finally, we return the response by using the xajaxResponse->getXML() method.

These actions ALWAYS occur in our server-side Ajax functions. But there's a bit more to tell you about the xajaxResponse class. Besides the xajaxResponse->addAssign() method there are some more. I have taken the list below from the xajax homepage and added some extra remarks.

  • addAssign($sTargetId,$sAttribute,$sData)
    Assigns the $sAttribute of the element identified by $sTargetId to $sData. With this we can replace the data of a specific element with new server-generated data.
    $objResponse->addAssign("contentDiv","innerHTML", "Some Text");
    $objResponse->addAssign("checkBox1","checked","true");
  • addAppend($sTargetId,$sAttribute,$sData)
    Appends $sData to the $sAttribute of the element identified by $sTargetId. This means the original content inside the attribute is preserved but new content is appended right after it.
    $objResponse->addAppend("contentDiv","innerHTML",
    "Some Text");
  • addPrepend($sTargetId,$sAttribute,$sData)
    Prepends $sData to the $sAttribute of the element identified by $sTargetId. This means the original content inside the attribute is preserved but new content is added right before it.
    $objResponse->addPrepend("contentDiv","innerHTML",
    "Some Text");
  • addReplace($sTargetId,$sAttribute,$sSearch,$sData)
    replaces all instances of $sSearch with $sData in the $sAttribute of the element identified by $sTargetId
    $objResponse->addReplace("contentDiv","innerHTML",
    "text","<strong>text</strong>");
  • addClear($sTargetId,$sAttribute)
    Clears the $sAttribute of the element identified by $sTargetId
    $objResponse->addClear("Input1","value");
  • addCreate($sParentId, $sTagname, $sId, $sType)
    Adds a new $sTagName child element to an existing element identified by $sParentId, and assigns it the id $sId and the optional type $sType.
    $objResponse->addCreate("form1","input", "pass", "password");
  • addRemove($sElementId)
    Removes the element identified by $sElementId from your application
    $objResponse->addRemove("div1");
  • addAlert($sMsg)
    Display a javascript alert box with $sMsg
    $objResponse->addAlert("The server said: Hi!");
  • addScript($sJS)
    Execute the JavaScript code $sJS. With this powerful method we can actually send javascript back to the client which is instantly executed.
    $objResponse->addAlert("var txt = prompt('get some text');");

Step 3: Wrapping it up

After setting up one or more functions nothing much will happen yet of course. We have to do some other things:

$objAjax = new xajax();
$objAjax->registerFunction('makeBold');
$objAjax->processRequest();

First we instantiate an xajax object. This objects handles all xajax processing. Secondly we register the function we created earlier on the xajax object We do this by using the method xajax->registerFunction(). Finally we can process the requests with the method xajax->processRequest().

'So what have we got now?', you may wonder. This doesn't really do much yet now does it? There's only one step left now to unleash our server-side magic onto the client side. After we've created our functions and we've setup our xajax object we can send out HTML content. We're now going to add the xajax magic to the page by using one simple line of code within our page's <head> section:

$objAjax->printJavascript();

Now we can finish off our page and use the functions we defined in the first steps directly from within the client-side part of our application. Considering our simple example we'd need to have some HTML element having the ID 'my_element':

<div id="my_element">I'm gonna have my ass kicked by xajax!&;t/div>

If we'd add a link to the page calling our backend-function, the text inside the above element would be made bold instantly without the browser window refreshing. We can call the backend xajax functions like this:

<a href="#" onclick="xajax_makeBold(document.getElementById('my_element'));">Kick his ass!</a>

That's it! We've now created our first Ajax powered link. Clicking it will do the magic. As you can see, backend functions can always be called from within client-side javascript by prepending xajax_ to the name we originally gave it. In our example we call xajax_makeBold(). We use document.getElementById('my_element') to target the element to update. We can specify any element and it's content will be enclosed by <b> and </b>.

Moving on

Is this all? Basically, yes! It's really that easy. Of course there's a bit more to xajax than you've seen in this article but the basic principles have been discussed. In order to further demonstrate both the power and the ease of use of xajax I've prepared four full-featured demonstrations. The demonstrations have fully documented source code with (hopefully) clear explanation of how everything works. Therefore, if this article has made you itching to get started, go to the demonstration mini-site and check out the examples.

Closing Notes

As you've probably noticed while reading this article and looking through the demonstrations, creating Ajax powered sites or applications isn't as hard as one may think. The xajax library makes Ajax with PHP as easy as writing normal PHP code. Of course there are plenty of other libraries that are definitely worth looking at. I simply picked xajax because of it's striking ease of use combined with remarkable powerful features. I hope this article has been useful for you.

Happy Ajaxing!

UPDATE: J. Max Wilson, the creator of xajax posts the following great news:

Hi. I'm the creator of the xajax php library. Thanks for the great presentation! Just wanted to let you all know that we've been working hard on a new release of xajax. We will be releasing a beta of the changes we've made later this week. Some of the new improvements include:

  • New error handling: Non-fatal PHP errors can now be easily trapped and written to a log file or displayed in an alert dialog in the client.
  • OOP: You can now register instance and static class methods to be callable through xajax. This is essential to make it easy to add xajax to many OOP CMS solutions.
  • Internationalization: xajax defaults to use UTF-8, but we've added the ability to set the charset to whatever you need to.
  • External Function Registration: you can now register functions in external .php files and xajax will dynamically include the file and call the function only if it is requested.

We've got a growing community of developers using xajax. We will soon be setting up at xajaxproject.org, but for now you can visit our forums at:

http://www.intuitivefuture.com/xajaxforums/

Feel free to ask questions and make feature requests.

J. Max Wilson

Thanks a lot J. Max! I'm gonna check it out. Stay tuned for a new story on what's new in xajax!
bookmarking

Commentary

Join the discussion! Leave a comment through the comment form below!

Got something to add to this?

Feel free to leave a comment on this site. You can use Textile and Emoticons. Your email address is only used to show a gravatar. Please stay on-topic and use common decency. Spammers will be shot in front of a live studio audience.

If you plan on posting code, use pastebin please and post a URL to the code. The comment processing doesn't deal very well with code. Sorry for the inconvenience.

Human comment spammers: don't bother posting your crap here. Comments are moderated and I won't let any of your shit through.

Remember personal info?
Yes
No

Trackbacks

If you have an interesting related post on your own site you can leave a trackback. As they say: 'a little AJAX a day keeps the spammers away' which is why you'll have to click below to generate a trackback key. The key will be valid for 15 minutes and can be used only once.

Ajax for campus-magazin
Für das noch junge Campus Magazin sollte in kürzester Zeit ein Fragebogen online geschalten werden. Da auch noch keine Webadresse vorhanden war, haben wir (Christian Aurich, Ronny Engelmann) über prosite.de eine DNS-Domain eingerichtet …Sent on 11 December '05 - 01:01 , via .: knoxmic // Ronny Engelmann :.

 

  • Featured Links
RockySomewhere near the Orion NebulaBookalicio.usGolden Gate BridgeThames River BankJackie and mePimpin' it