print Tutorial 3: Adding Ajax controls to a controller

Adding the ajax functions

The final step is to add the HTML code to use the ajax function. This will be added to the main guestbook.html.tpl file.

First off, the xajaxScript variable needs to be added to the header. This was assigned in the guestbookView as (in Smarty) {$xajaxScript} and this will need placing in between the < head > tags.

Then in the body of the page we need to add our element that will receive the data from the ajax call. This could be hidden by CSS (which would require additional xajax assigns to set the visibility) or for this example, it will just contain some holding text.

The xajax function we assigned in the controller will be available as xajax_TheMethodName. These can be aliased by changing the third parameter in the controller. For more options it is strongly suggested to check out the xajax documentation.

Note the return false; on the ajax call. This is to stop any submissions - even though this is an input button and not a form submit, we do not want a submission to take place.

Finally; create a randomComment.html.tpl template which for this example contains the usual Smarty printr for the object:

{$oComment|printr}

And that's it! All done. Save all the changes and click the button to see a random comment being inserted. Parameters can be passed in either from a form using xajax_values or as actual parameters. So we could add a limit to our random comment and list 2 or 3. The parameter(s) would need to be sanity checked and the appropriate changes made to the controller method to allow for parameters.

Hopefully you can see how easy this is to add with the minimum of effort. The xajax requests can then be made as complex as you need then to be. For example: check out some of the admin code, in particular the mvcDaoController that handles many of the applets through a single interface.

You can download the files from this tutorial as a Zip file.