Easy Ajax for the masses with xajax
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!
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 PHP 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 xajax there's very, VERY little javascript 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 Ajax 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
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:
- the name of an HTML element in our page
- The property of the element we want to change client-side
- The stuff we want to send to the client
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':
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:
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:Thanks a lot J. Max! I'm gonna check it out. Stay tuned for a new story on what's new in xajax!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
Filed under: programming
Number of comments:
Number of trackbacks:
Tagged with: 







At 12 November '05 - 08:06 Blues wrote:
At 12 November '05 - 08:14 Marco wrote:
Yes it was a shame the time was up. I actually planned to show some more funky stuff from the Typo theme I’m currently creating for the contest (Typo is packed with really cool Ajax stuff) but unfortunately I didn’t get the chance…
At 12 November '05 - 13:04 bosmeneer wrote:
And I thought Opera was the best browser.. ;)
At 14 November '05 - 01:07 stefan wrote:
1. From the examples I gather that ajax calls are always forwarded to the same file they’re called from? Is there a way to centralize all ajax-calls to a single file? It’s my experience that having a single entry point for ajax calls makes the code cleaner ;)
2. You mentioned that AJAX allows for richer user interfaces. Though I agree for people such as you and me, I am quite bothered with the implications on accessibility. Someone with no javascript, for instance, is most of the times unable to use websites that use a lot of ajax. Most websites don’t offer any alternatives for those without javascript. Usually accessibility and usability go hand in hand, but in this case, they’re two completely seperate entities and though AJAX enhances usability (for “regular users, clearly not for users with certain disabilities/challenges) it definitely breaks any form of accessibility. Or am I missing something here?
At 14 November '05 - 01:17 Marco wrote:
As for question 2: It’s always up to the developer / UI designer to take care of accessibility. My form submission example works without javascript as well. Validation can be done server side as well (the age form example) and live search isn’t an ‘essential’ feature. Users can still enter ‘Amsterdam’ in the field and submit the form even when the whole livesearch thing isn’t working. In my example it’s fairly easy to keep things ‘accessible’. If you create advanced drag & drop Ajax frontends this challenge becomes harder. I fully agree with you it should be taken care of. A non-javascript fallback should be available at all times!
At 14 November '05 - 07:02 Max wrote:
That being said, I second the question for a more centralized approach — I’m not the biggest fan of doing all kinds of dynamic JavaScript, especially if most of it isn’t dynamic at all. That’s just pissing away server CPU cycles. But I haven’t been digging the internals much, yet, so maybe that’s pretty easy to do.
Always nice to know that a piece of software I like is “approved” =]
At 14 November '05 - 07:05 Marco wrote:
At 15 November '05 - 14:53 Max wrote:
At 15 November '05 - 18:36 Stoyan wrote:
While I agree with Stefan and Marco that there should always be a non-js fallback of anything AJAX, I believe the approach should be even more conservative. I mean there are too ways of thinking about a page. – approach one – build the coolest ever ajax/js interface and then add fallback – noscript tag or just turn off javascript and make sure it still works – approach two – basically the opposite, code the html then enhance with js/ajax
I think approach two is preferable. With approach one you can put all your energy (time, budget) tweaking the coolest AJAX interface ever, then have nothing left for the fallback and just dismiss it like: “well, everyone supports XMLHTTP these days”.
In approach two you get the site working and usable in Lynx first (meaning it’s search-engine spiderable), then whatever resources you have (energy, time, budget) you pour into the AJAX pit :)
This way of thinking is inherited by the idea that the web sites consist of: – content (HTML) – style (CSS) – behaviour (JavaScript)
And should be built in this order and never mixed. After all content is king, right, so no behavioural elements should obfuscate your content.
Of course this is a nice theory and if I’m to fully follow the separation of content and behaviour, that will mean no more onclick, onmouseover, etc, but attaching events instead.
But at the end, as someone said: “In theory there’s no difference between theory and practice, but in practice there is…” :)
At 15 November '05 - 19:27 Stoyan wrote:
onclick=“xajax_makeBold(document.getElementById(‘my_element’));”
should be
onclick=“xajax_makeBold(document.getElementById(‘my_element’).value);”
Because makeBold() expects a string, right? Or I missed something?
At 21 November '05 - 10:06 J. Max Wilson wrote:
Edit: I added the rest of this important comment to the posting itself. Thanks J. Max!
At 05 December '05 - 04:32 stefan wrote:
At 05 December '05 - 14:25 Dustin Diaz wrote:
Not to take away any glory, but c’mon, learn some JavaScript there eh ;)
Anyway, aside from that, this is a very beautiful implementation written for php developers. Just like prototype, but in PHP. Got it bookmarked :)
At 06 December '05 - 02:08 Anonymous wrote:
There are certainly other classes to look after..
Of course there is HTML_AJAX ( http://wiki.bluga.net ) because it is a part of the Pear repository.
However, XOAD ( http://www.xoad.org ) is also very very sweet but this requires you to write a lot of JS.
And as far as using Ajax in a website.. I only use it in my cms in which i force my users to have an ajax compatible browser..
At 06 December '05 - 02:13 Marco wrote:
Also: There are many nice ajax libraries out there but this tutorial happens to be about xajax. Of course I’m looking at other developments as well.
At 15 December '05 - 11:21 Will wrote:
Love it!
At 22 January '06 - 14:45 Daniel P Dykes, Rogue Connect wrote:
At 22 January '06 - 14:57 Marco wrote:
I guess it’s the first dating service I’ve seen that makes such an extensive use of tagging. Very nice indeed!
At 23 January '06 - 04:52 VRony wrote:
At 23 January '06 - 04:58 Marco wrote:
At 24 January '06 - 04:47 VRony wrote:
Thnx
Do you have some examples or url’s concerning forms combo select boxes attach to a database where a db can be updated after making selection(s) ?
Love your work…
At 03 February '06 - 02:51 Bernard wrote:
It is possible to direct ajax calls to another file than the ‘current’ one. Nothing complicated. Basically it comes down to:
In the calling file
require_once(“xajax/xajax.inc.php”);
$xajax = new xajax(“allajaxfunctions.php”);
$xajax->registerFunction(‘first_function_you_need’);
$xajax->registerFunction(‘second_function_you_need’);
...
...
And then in the ‘allajaxfunctions.php’ file:
require_once(“xajax/xajax.inc.php”);
function first_function_you_need()
{
...
}
function second_function_you_need()
{
...
}
...
$xajax = new xajax();
// register all functions in this file:
$xajax->registerFunction(‘first_function_you_need’);
$xajax->registerFunction(‘second_function_you_need’);
...
$xajax->processRequests();
...
Hope this helps,
Bernard
At 05 February '06 - 15:35 samira similan wrote:
line :
In file “processform.php” just write the code to handle the form “submit” the usualy way ?
Thanks.
At 05 February '06 - 22:06 Marco wrote:
At 28 February '06 - 20:34 Gustavo wrote:
Kick his ass!
At 27 March '06 - 01:48 Rémy wrote:
Skilled PHP developeres are often unable to develop powerful Javascript functionalities.
XAJAX puts everybody on the same level : no need to write ugly javascripts, no need to write huge PHP scripts :)
The best of the two worlds ^^
So, no need to say “hey dude ! learn some javascript, you’re a looser !” because ONLY bases of javascript are useful in the beautiful of the WEB 2.0 world ;)
At 27 March '06 - 12:45 zul wrote:
At 20 April '06 - 05:59 Nagesh wrote:
onclick=”xajax_makeBold(document.getElementById(‘my_element’));”
should be
onclick=”xajax_makeBold(document.getElementById(‘my_element’).value);”
Because makeBold() expects a string, right? Or I missed something?
REPLY==>
the above change will also not work..
it should be
onclick=”xajax_makeBold(document.getElementById(‘my_element’).innerHTML);”
At 08 May '06 - 02:43 Berry Langerak wrote:
At 19 May '06 - 08:43 cory wrote:
“
Error: xajax_doTimestamp is not defined
Source File: http://localhost:81/ajax/xajax-demo/demo..
Line: 1
“
At 07 June '06 - 14:29 alvaro wrote:
thank for all.
At 15 June '06 - 06:18 Martin wrote:
Am I right, that the answer to stefan’s question #1 (november 05) is now obsolete? The target URI can be set by the first parameter of the constructor or via the method setRequestURI (string $sRequestURI).
Just for better understanding…
At 19 June '06 - 14:13 BigBrownChunx wrote:
http://wiki.xajaxproject.org/Es:Main_Pag..
There’s also a Chinese version in the works at
http://wiki.xajaxproject.org/Zh:Main_Pag..
Martin, yes you can use setRequestURI, and you can also use registerExternalFunction to put all your xajax functions in another PHP file.
At 21 June '06 - 22:49 njuguo wrote:
At 23 June '06 - 05:56 kverko wrote:
At 03 July '06 - 08:10 Nelson wrote:
$objResponse->addAlert(“var txt = prompt(‘get some text’);”);
but
$objResponse->addScript(“var txt = prompt(‘get some text’);”);
At 17 July '06 - 13:52 Gordon Mackay wrote:
At 09 August '06 - 19:54 Rey wrote:
Untitled Document
Start
xajax_display(); // call the helloWorld function to populate the div on load
At 09 August '06 - 20:06 rey wrote:
Untitled Document
Start
xajax_display();
At 22 September '06 - 23:45 Sandro from Italy wrote:
(which happens very often with italian strings) because such characters are changed to ‘?’ . Is there any fix?
At 12 October '06 - 04:42 Grigory wrote:
http://myjoomla.ru/demo_ru/demonstratie...
At 11 December '06 - 07:38 trash wrote:
function loginProcess(){
[...]
$myclass->lang[‘somelangoption’];
[...]
}
can you explain me how to include,initialize xajax to use it into my class, thank you!
At 11 December '06 - 18:05 Francis wrote:
How can i used xajax in my file uploader? is it possible to have uploader in my form using xajax? how is the process? thanks.
francis
At 23 January '07 - 00:32 Ahmet wrote:
Ahmet
At 24 January '07 - 11:28 Jimy wrote:
At 26 April '07 - 00:17 Inder Singh wrote:
Iam a PHP developer ….Iam found my interest in ajax…..And these entries are very helpful for the developers for growing their knowledge..Thanks for this article…..
Nice combination of php and javascript…
At 26 April '07 - 00:20 Inder Singh wrote:
Nice combination of php and javascript…
At 03 May '07 - 00:00 Mike wrote:
At 08 May '07 - 03:35 Sundar wrote:
At 11 June '07 - 22:32 Alex wrote:
Click Me
instead of
Click Me
for Text links?
At 12 June '07 - 02:25 Marco wrote:
At 13 June '07 - 16:37 Alex wrote:
My previous post was asking about the use of href=“javascript:” over onclick= for text links. I was trying to provide examples (click me) but I didn’t use any code tags so the post rendered incorrectly and I couldn’t edit it.
Anyway I have found that the later versions of xajax will only allow onclick=
Cheers
At 10 July '07 - 02:44 jasmine wrote:
for eg,
$objResponse->addAlert(“The server said: Hi!”);
Even this also not working in MAC’s Firefox browser. can u help me, to execute in Mac?
At 26 July '07 - 01:20 dirk jan wrote:
this is the stuff that makes the internet a great place.
something else,
when looking at your site design,
i remembered i made a rendering of my own designed bridge,
for a architectural design contest back in 1998 (last century rendering…)
take a look, dont you think it is similar to the one you used?
http://youtube.com/watch?v=oWEAlKmFwV8
At 29 August '07 - 00:17 christiane wrote:
I think the hype is over and you’re better off now with using ajax in rare situations. There’s not too much value in c/s communications on websites – besides the “cool and geeky effect”.
I program my rare ajax techs by hand with few lines of javascript and little php – and for me it’s more easy than learning a frameworks API.
At 12 October '07 - 08:43 Dirk Jan Luiting wrote:
version 2.0 av DOMAssistant: http://www.robertnyman.com/2007/09/20/re..
At 26 October '07 - 22:35 Ramesh Kumar wrote:
At 24 November '07 - 17:25 ragebeing wrote:
I’m going to try with codeigniter.
At 02 April '08 - 15:33 Aaron wrote:
registerFunction(‘makeBold’);
$objAjax->processRequest();
?>
I’m gonna have my ass kicked by xajax
Kick his ass!
Kick his ass!
At 19 March '09 - 22:11 Mira wrote: