You must first sign up to be able to contribute.

Version 2 (modified by joncol, 11 years ago)
formatting correction


Using AJAX to retrieve data and fire actions is an extremely good way of improving the responsiveness of a web application. Below is a description of some of the approaches I use to implement it.

Before going further I would like to highlight:

- I would not consider myself to be a guru in any of the technologies involved

- Some aspects of the methods do not align to the Symfony framework very well

- Forethought must be given to appropriate accessibility of site, but is not contained here

Been a solid framework for AJAX interactions and included with Symfony, Prototype is a good facilitator and is used in the examples below.

I prefer to group all ajax actions into a common module, or if a ajax_<modulename> if <modulename> has enough 'AJAX' interactions to merit it.

This allows:

- Common 'view' configuration

- Common Security Measures

- Aligned Validation

View Configuration Of course the first thing done is to turn layout off, in addition common 'simple' templates can be used by a number of actions to output appropriate content. I refer to a template to output JSON of course. Whilst many will shout the JSON can be encapsulated in the response header, there are a number of cases where the header does not have the capacity to hold the appropriate content (furthermore the capacity of header elements varies between browsers, i think). Another reason to use response bodies is to contain debug before inserting 'return sfView::HEADER_ONLY;'

Security Measures Now I am not going to discuss the revelence or effectiveness of the measures, but there's nowt wrong with pinning down how your application is interacted with. Firstly, I like to use the POST method for all AJAX requests; this is because most requests do convey data, and any robot trawling your site for url is likely to use GET when it starts sniffing around. A request header attribute that the Prototype library automatically enters in requests is X_REQUESTED_WITH = XMLHttpRequest. This is another filting point (if you wanted to go further, you could add further custom headers, however anyone going that would inspect the source to ascertain the key. If your data is that precious, you should ensure the client is authenticated in some way).

Validation Keeping AJAX actions in the same module provides a great amount of visibility relating to what validation is being conducted upon incoming vars. Furthermore as AJAX will no doubt be dealing with JS/PHP/custom dataformats and structures, custom validators can be employed to ensure the more complex strings are valid. I use a validator to ensure a serialized PHP array generated by JS is well formed before I allow the action to have it.