The "Hello World" of Ajax and PHP

The "Hello World" of Ajax can be intimidating because there is more than one language involved: PHP and JavaScript. Unlike in a traditional web application where most of the presentation and data processing is handled by PHP (or any server-side language for that matter), in Ajax applications PHP only creates the data and it is up to the JavaScript on the client side to interpret that data.

If you are unfamiliar with PHP 5 you may want to take a moment to look at the Appendix for an overview of what relevant features have changed between versions 4 and 5.

After receiving a request to an Ajax-enabled PHP page, the server then returns the page as it normally would. The magic occurs when we include JavaScript in the served page that is linked to actions. Once one of those actions occurs, an asynchronous request will be made to the server. The server then returns the requested data, which JavaScript can act on accordingly (see Figure 1).

Generic sequence diagram for a typical Ajax application

Figure 1. Generic sequence diagram for a typical Ajax application

We can see that the actor (client viewing your web page) makes a request to view the selected page where he is served a mix of HTML, JavaScript, and most likely images. The JavaScript is designed so that by using Ajax the user can perform an action and receive data in return without leaving or reloading the page he is currently viewing.

Because the page is being ...

Get Ajax with PHP 5 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.