Book Image

AJAX and PHP: Building Responsive Web Applications

By : Mihai Bucica, Cristian Darie, Bogdan Brinzarea, Filip Chereches-Tosa, Philippe Wauthier
Book Image

AJAX and PHP: Building Responsive Web Applications

By: Mihai Bucica, Cristian Darie, Bogdan Brinzarea, Filip Chereches-Tosa, Philippe Wauthier

Overview of this book

Assuming a basic knowledge of PHP, XML, JavaScript and MySQL, this book will help you understand how the heart of AJAX beats and how the constituent technologies work together. After teaching the foundations, the book will walk you through numerous real-world case studies covering tasks you'll be likely to need for your own applications: Server-enabled form-validation page Online chat collaboration tool Customized type-ahead text entry solution Real-time charting using SVG Database-enabled, editable and customizable data grid RSS aggregator application A server-managed sortable list with drag&drop support using the JavaScript toolkit The appendices guide you through installing your working environment, using powerful tools that enable debugging, improving, and profiling your code, working with XSLT and XPath. From the Author, Cristian Darie AJAX and PHP: Building Responsive Web Applications is mainly a book for beginners, but when designing its contents we tried to find the ideal blend of topics that would help both novice and experienced web developers make a big step forward. One customer was very kind to let us know, through a review, that we succeeded: "The theory behind all the technologies used is very clearly explained, without boring you with details about obvious things. Right from the first chapter you start learning by examples. The examples can be easily adapted to many web projects and they cover stuff that is both useful and fun." Here are a few examples of such "useful and fun" things that you can find in this book: details on using proxy scripts to work around the security measures in modern browsers client-side and server-side code that doesn't break when fed with special characters (such as <, ", etc) code that works efficiently with Internet Explorer 5, 6 and 7, Firefox, Opera, Safari, and others a very quick introduction to SVG, the new rebel kid of the web (and of the house) client-server communication based on message queues that guarantee that your messages aren't lost on the way, and arrive in the intended order at the destination server-side state management techniques that use query string parameters and database records to keep track of your client's activity simple yet effective error-handling structures that combine JavaScript code and PHP code to report when something bad happens on the client or on the server a live errata page that is updated as soon as anyone reports a suggestion or a correction a friendly AJAX tutorial and many case studies that teach you how to use JavaScript, PHP, MySQL and XML together in order to achieve wonderful results The book's authors and the publisher are listening to your feedback, and appreciate when you invest some time to let them know what you think. The first result of this collaboration is an updated version of the AJAX Chat case study that uses (and teaches) JSON instead of XML. Find this new chapter in the code download or on my website. Thanks for reading such a long message. Have fun!" Cristian Darie.
Table of Contents (17 chapters)
About the Authors
About the Reviewers

Understanding AJAX

AJAX is an acronym for Asynchronous JavaScript and XML. If you think it doesn’t say much, we agree. Simply put, AJAX can be read “empowered JavaScript”, because it essentially offers a technique for client-side JavaScript to make background server calls and retrieve additional data as needed, updating certain portions of the page without causing full page reloads. Figure 1.4 offers a visual representation of what happens when a typical AJAX-enabled web page is requested by a visitor:

Figure 1.4: A Typical AJAX Call

When put in perspective, AJAX is about reaching a better balance between client functionality and server functionality when executing the action requested by the user. Up until now, client-side functionality and server-side functionality were regarded as separate bits of functionality that work one at a time to respond to user’s actions. AJAX comes with the solution to balance the load between the client and the server by allowing them to communicate in the background while the user is working on the page

To explain with a simple example, consider web forms where the user is asked to write some data (such as name, email address, password, credit card, etc) that has to be validated before reaching the business tier of your application. Without AJAX, there were two form validation techniques. The first was to let the user type all the required data, let him or her submit the page, and perform the validation on the server. In this scenario the user experiences a dead time while waiting for the new page to load. The alternative was to do this verification at the client, but this wasn’t always possible (or feasible) because it implied loading too much data on the client (just think if you needed to validate that the entered city and the entered country match).

In the AJAX-enabled scenario, the web application can validate the entered data by making server calls in the background, while the user keeps typing. For example, after the user selects a country, the web browser calls the server to load on the fly the list of cities for that country, without interrupting the user from his or her current activity. You’ll find an example of AJAX form validation in Chapter 4.

The examples where AJAX can make a difference are endless. To get a better feeling and understanding of what AJAX can do for you, have a look at these live and popular examples:

You’ll see even more examples over the course of this book.


Just as with any other technology, AJAX can be overused, or used the wrong way. Just having AJAX on your website doesn’t guarantee your website will be better. It depends on you to make good use of the technology.

So AJAX is about creating more versatile and interactive web applications by enabling web pages to make asynchronous calls to the server transparently while the user is working. AJAX is a tool that web developers can use to create smarter web applications that behave better than traditional web applications when interacting with humans.

The technologies AJAX is made of are already implemented in all modern web browsers, such as Mozilla Firefox, Internet Explorer, or Opera, so the client doesn’t need to install any extra modules to run an AJAX website. AJAX is made of the following:

  • JavaScript is the essential ingredient of AJAX, allowing you to build the client-side functionality. In your JavaScript functions you’ll make heavy use of the Document Object Model (DOM) to manipulate parts of the HTML page.

  • The XMLHttpRequest object enables JavaScript to access the server asynchronously, so that the user can continue working, while functionality is performed in the background. Accessing the server simply means making a simple HTTP request for a file or script located on the server. HTTP requests are easy to make and don’t cause any firewall-related problems.

  • A server-side technology is required to handle the requests that come from the JavaScript client. In this book we’ll use PHP to perform the server-side part of the job.

For the client-server communication the parts need a way to pass data and understand that data. Passing the data is the simple part. The client script accessing the server (using the XMLHttpRequest object) can send name-value pairs using GET or POST. It’s very simple to read these values with any server script.

The server script simply sends back the response via HTTP, but unlike a usual website, the response will be in a format that can be simply parsed by the JavaScript code on the client. The suggested format is XML, which has the advantage of being widely supported, and there are many libraries that make it easy to manipulate XML documents. But you can choose another format if you want (you can even send plain text), a popular alternative to XML being JavaScript Object Notation (JSON).

This book assumes you already know the taste of the AJAX ingredients, except maybe the XMLHttpRequest object, which is less popular. However, to make sure we’re all on the same page, we’ll have a look together at how these pieces work, and how they work together, in Chapter 2 and Chapter 3. Until then, for the remainder of this chapter we’ll focus on the big picture, and we will also write an AJAX program for the joy of the most impatient readers.


None of the AJAX components is new, or revolutionary (or at least evolutionary) as the current buzz around AJAX might suggest: all the components of AJAX have existed since sometime in 1998. The name AJAX was born in 2005, in Jesse James Garret’s article at, and gained much popularity when used by Google in many of its applications.

What’s new with AJAX is that for the first time there is enough energy in the market to encourage standardization and focus these energies on a clear direction of evolution. As a consequence, many AJAX libraries are being developed, and many AJAX-enabled websites have appeared. Microsoft through its Atlas project is pushing AJAX development as well

AJAX brings you the following potential benefits when building a new web application:

  • It makes it possible to create better and more responsive websites and web applications.

  • Because of its popularity, it encourages the development of patterns that help developers avoid reinventing the wheel when performing common tasks.

  • It makes use of existing technologies.

  • It makes use of existing developer skills.

  • Features of AJAX integrate perfectly with existing functionality provided by web browsers (say, re-dimensioning the page, page navigation, etc).

Common scenarios where AJAX can be successfully used are:

  • Enabling immediate server-side form validation, very useful in circumstances when it’s unfeasible to transfer to the client all the data required to do the validation when the page initially loads. Chapter 4 contains a form validation case study.

  • Creating simple online chat solutions that don’t require external libraries such as the Java Runtime Machine or Flash. You’ll build such a program in Chapter 5.

  • Building Google Suggest-like functionality, like an example you’ll build in Chapter 6.

  • More effectively using the power of other existing technologies. In Chapter 7, you’ll implement a real-time charting solution using Scalable Vector Graphics (SVG), and in Chapter 10, you’ll use an external AJAX library to create a simple drag‑and‑drop list.

  • Coding responsive data grids that update the server-side database on the fly. You’ll create such an application in Chapter 8.

  • Building applications that need real-time updates from various external sources. In Chapter 9, you’ll create a simple RSS aggregator.

Potential problems with AJAX are:

  • Because the page address doesn’t change while working, you can’t easily bookmark AJAX-enabled pages. In the case of AJAX applications, bookmarking has different meanings depending on your specific application, usually meaning that you need to save state somehow (think about how this happens with desktop applications—there’s no bookmarking there).

  • Search engines may not be able to index all portions of your AJAX application site.

  • The Back button in browsers, doesn’t produce the same result as with classic web applications, because all actions happen inside the same page.

  • JavaScript can be disabled at the client side, which makes the AJAX application non-functional, so it’s good to have another plan in your site, whenever possible, to avoid losing visitors.

Finally, before moving on to write your first AJAX program, here are a number of links that may help you in your journey into the exciting world of AJAX:

The list is by no means complete. If you need more online resources, Google will surely be available to help. In the following chapters, you’ll be presented with even more links, but more specific to the particular technologies you’ll be learning about.