Okay so I have been messing around with all this ajax stuff recently. Now being a big fan of SMARTY I was reluctant to go and write my own templating system, and intergrating javascript into some of the existing smarty templates I had was a bit of a pain in the ass. But I really wanted to give this AJAX stuff a go.
After trying various different ajax scripts and implementatons, I settled on XAjax to work with PHP. The main reason was that they seemed to be the easiest to intergrate with Smarty.
So down to the nuts and bolts of it.
require_once(INCLUDESDIR. '/3rdparty/Xajax/xajax.inc.php');
$xajax = new xajax();
// Send our xajax requests to a certain server
$xajax->setRequestURI("form-processor.php");
$xajax->registerFunction("validate-field");
$xajax->processRequests();
$smarty->assign('xajax_javascript', $xajax->getJavascript());
$smarty->display('web/common/header.tpl');
So lets go this bit by bit just so that we are clear.
No an important bit here. If like me you are sending your requests to a separate script, you must include the Xajax library, you must have xajax registered the functions and you must call xajax->processRequests();
A function, for those that don’t know can be anything you want to do. The validate one looks like this;
public function validate-field($arg1) {
$objResponse = new xajaxResponse();
if(!$arg1, !$arg2) {
return false;
}
$objResponse->addClear("messages","innerHTML");
$objResponse->addAssign('messages', 'innerHTML', "Form was validated");
return $objResponse->getXML();
}
You must return the $objResponse->getXML(), otherwise, how is XAJAX supposed to know what to do?
So on my form, I have a on blur event that simply valiades the filed after the user moves away from the field
This simple gets the value of the field and passes it to xajax whihc then calls my function. Simple right.
Now I have actually got it to send messages like processing data, and then display an error message, perhaps I will put up an example of those when I get a chance.
BTW this is a very very simplifed example of how quick it is to add XAJAX into your scripts. However please note that it can be quite complex to do this, and you should sit and plan your application correctly and its data flow. Also remember don’t use AJAX just because its cool to do so, use it because there is actually a need to use it.