Book Image

AJAX and PHP: Building Modern Web Applications 2nd Edition

By : Audra Hendrix, Bogdan Brinzarea, Cristian Darie
Book Image

AJAX and PHP: Building Modern Web Applications 2nd Edition

By: Audra Hendrix, Bogdan Brinzarea, Cristian Darie

Overview of this book

<p>AJAX enables interactive interfaces that can replace traditional user interfaces. Enhance the user experience of your PHP website using AJAX with this practical and friendly tutorial! This book is the most efficient resource you can get to enter the exciting world of AJAX with PHP. Based on numerous examples and detailed case studies, this AJAX with PHP tutorial will build your foundation knowledge for creating faster, better web applications.<br /><br />Detailed description<br />The best AJAX tutorial for PHP developers has been completely rewritten to be your friendly guide to modern Web 2.0 development techniques! AJAX and PHP: Building Modern Web Applications, 2nd Edition covers every significant aspect of creating and maintaining AJAX and PHP applications.<br /><br />This book will teach you how to use PHP, JavaScript, MySQL and jQuery to build modern, responsive web applications. After building a strong foundation, the book will walk you through numerous real-world case studies covering techniques you’ll be likely to need for your own applications:</p> <ul> <li>Learn how to write unobtrusive, degradable, portable, SEO-friendly AJAX code</li> <li>Understand the object-oriented model of JavaScript and JSON</li> <li>Learn how to use the jQuery JavaScript library by going through two complete case studies</li> <li>Debug your AJAX and PHP code using modern tools</li> <li>Assess the security implications of writing AJAX code and avoid security risks such as cross-site scripting</li> <li>Learn advanced AJAX and PHP patterns and techniques such as predictive fetching, progress indicator, graceful degradation, cross-domain calls, and more</li> <li>Understand the complete client-server mechanism by going through complete, step-by-step case studies, including AJAX Form Validation, and AJAX Online Chat and AJAX Editable DataGrid with jQuery</li> </ul>
Table of Contents (16 chapters)
AJAX and PHP
Credits
About the Authors
About the Reviewer
Preface
Index

The world of AJAX


AJAX is an acronym for Asynchronous JavaScript and XML. The key element here is Asynchronous. Simply put, AJAX offers a technique to make background server calls via JavaScript and retrieve additional data as needed, updating 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

AJAX solves the balance between the client and server by allowing them to communicate in the background while the user is working on the page.

Consider web registration forms where the user is asked to enter data (such as name, email address, password, credit card number, and so on) that must be validated before proceeding to the next step of the registration process. There are three possible ways to implement this:

  • Let the user type all the required data, submit the page, and then perform the validation on the server. If the validation doesn't succeed, the server sends back the (sometimes empty) form, asking the visitor to correct the invalid entries. In this scenario, the user experiences dead time (a delay) between submitting and waiting for response.

  • Do the validation at the client side by using JavaScript. The user is warned about invalid data and corrects the invalid entries before submitting the form. This technique only works for very simple validation that doesn't require additional data from the server. This technique also doesn't work when using proprietary or secret validation algorithms that can't be transferred to the client in the form of JavaScript code.

  • Use AJAX form validation so that the web application can validate the entered data in the background, while the user fills the form. For example, after the user types the first letter of the city, the web browser calls the server to load "on-the-fly" a list of cities that start with that letter.

When we wrote the first edition of this book, there were only a few AJAX-enabled applications on the Web. Now, the majority of modern websites have implemented AJAX features. Here are a few of the most popular:

Figre 1-5 displays the Google autocompletion feature:

Figure 1-5: Google autocompletion feature

In conclusion, AJAX is about creating smarter web applications (that behave better than traditional web applications when interacting with humans) by enabling web pages to make asynchronous calls to the server transparently while the user is working.

What is AJAX made of?

The technologies AJAX is made of are already implemented in all modern web browsers, so the client doesn't need to install any extra modules to run an AJAX website. AJAX is made up of the following:

  • JavaScript, the essential ingredient of AJAX, allows you to build the client-side functionality. In the JavaScript functions, we'll use the Document Object Model (DOM) to manipulate parts of the HTML page.

  • The XMLHttpRequest object, the component that enables JavaScript to access the server asynchronously in the background.

  • Except for the simplest applications, a server-side technology is required to handle requests that come from the JavaScript client. In this book, we'll use PHP to perform the server-side part of the job.

Note

None of the AJAX components are as new, or revolutionary (or at least evolutionary), as the buzz around AJAX might suggest. The most recent AJAX component is XMLHttpRequest, which was released by Microsoft sometime in 1999. You can read more on the history of AJAX at http://en.wikipedia.org/wiki/AJAX.

For client-server communication, the JavaScript client code and the PHP server-side code need a way to pass data and understand that data. Passing the data is the simple part. Using the XMLHttpRequest object, the client script accessing the server 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 client code. The format can be simple text, but in practice, you'll need a data format that can be used to pass structured data. The two popular data exchange formats used in AJAX applications are XML and JavaScript Object Notation (JSON).

This book assumes that you have previous experience with the AJAX ingredients, except maybe the XMLHttpRequest object. However, in order to make sure we're all on the same page, we'll have a look at how these pieces work, and how they work together, in Chapter 2, JavaScript and the AJAX Client. For the remainder of this chapter, we'll focus on the big picture, and for the joy of the most eager readers, we will also write an AJAX program.

Uses and misuses of AJAX

As noted earlier, AJAX can improve your visitors' experience with your website, but it can also worsen it when used inappropriately. Unless your application has really special requirements, it's wise to let your users navigate your content using good old hyperlinks. Web browsers have a long history of dealing with content navigation, and web users have a long history of using these browsers. In the vast majority of cases, AJAX is best used in addition to the traditional web development paradigms, rather than changing or replacing them.

Let's quickly review the potential benefits that AJAX can bring to your projects:

  • It makes it possible to create responsive and intuitive web applications

  • It encourages the development of patterns and frameworks that reduce the development time of common tasks

  • It makes use of the existing technologies and features that are already supported by all modern web browsers

  • It makes use of many existing developer skills

Potential problems with AJAX are:

  • Adding AJAX to your site without forethought or reason can detract from your site's effectiveness. Increased awareness of usability, accessibility, web standards, and search engine optimization will help you make good decisions when designing and implementing websites.

  • Because search engines don't execute any JavaScript code when indexing a website, they cannot index any content generated with JavaScript. If search engine optimization is important for your website, you may need to forego using AJAX for content delivery and navigation and use it only sparingly in those parts of your site that won't impact search engine indexing.

  • JavaScript can be disabled at the client side, which renders the AJAX code non-functional.

  • Bookmarking AJAX-enabled pages requires planning. Typically AJAX applications run inside a web page whose URL doesn't change in response to user actions, in which case, you can only bookmark the entry page. To enable bookmarking, you must dynamically add page anchors by using your JavaScript code, such as in http://www.example.com/my-ajax-app.html#Page2. You also need to create supporting code that loads and saves the state of your application through the anchor parameter.

  • The Back and Forward buttons in browsers don't produce the same result as with classic websites, unless your AJAX application is programmed to support loading and saving states.

To enable AJAX page bookmarking, and the Back and Forward browser buttons, you can use frameworks such as Really Simple History by Brad Neuberg (http://codinginparadise.org/projects/dhtml_history/README.html).

Following the popularity of AJAX, a large number of AJAX-enabled frameworks and toolkits have been developed that include common and tested features. Let's take a look at a few.

Resources and tools

AJAX enjoys an active community and a veritable plethora of resources, guides, toolkits, frameworks, forums, and tutorials. Whether you're a veteran developer or working with AJAX for the first time, it's well worth your time to peruse these resources.

We are listing a few places to get you started that may help you in your journey into the exciting world of AJAX. Some are server-agnostic, while others are specifically created for ASP.NET, Java, PHP, Coldfusion, Flash, and Perl backends. Among the most popular server-agnostic toolkits are Dojo (http://dojotoolkit.org), Prototype (http://prototypejs.org/), script.aculo.us (http://script.aculo.us), and jQuery (http://jquery.com/)—which you'll be using in this book as well.

For starters, here are a few useful generic AJAX resources:

The list is by no means complete. If you need more online resources, search engines will be of help.