AJAX and PHP Building Responsive Web Applications Enhance the user experience of your PHP website using AJAX with this practical tutorial featuring detailed case studies Cristian Darie Bogdan Brinzarea Filip Cherecheş-Toşa Mihai Bucica BIRMINGHAM - MUMBAI AJAX and PHP Building Responsive Web Applications Copyright © 2006 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: March 2006 Production Reference: 1210206 Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 1-904811-82-5 www.packtpub.com Cover Design by www.visionwt.com Credits Authors Cristian Darie Brinzarea Bogdan Filip Cherecheş-Toşa Mihai Bucica Reviewers Emilian Balanescu Paula Badascu Technical Editor Jimmy Karumalil Editorial Manager Dipali Chittar Development Editor Cristian Darie Indexer Ashutosh Pande Proofreader Chris Smith Production Coordinator Manjiri Nadkarni Cover Designer Helen Wood About the Authors Cristian Darie is a software engineer with experience in a wide range of modern technologies, and the author of numerous technical books, including the popular "Beginning E-Commerce" series. Having worked with computers since he was old enough to press the keyboard, he initially tasted programming success with a first prize in his first programming contest at the age of 12. From there, Cristian moved on to many other similar achievements, and now he is studying distributed application architectures for his PhD degree. He always loves hearing feedback about his books, so don't hesitate dropping a "hello" message when you have a spare moment. Cristian can be contacted through his personal website at www.cristiandarie.ro. Cristian would like to express a big "thank you!" to his co-authors, Bogdan, Filip, and Mihai and to the Technical Editor of the book, Jimmy, for the hard work they've put into building this wonderful book. Bogdan Brinzarea has a strong background in Computer Science holding a Master and Bachelor Degree at the Automatic Control and Computers Faculty of the Politehnica University of Bucharest, Romania and also an Auditor diploma at the Computer Science department at Ecole Polytechnique, Paris, France. His main interests cover a wide area from embedded programming, distributed and mobile computing, and new web technologies. Currently, he is employed as an Alternative Channels Specialist at Banca Romaneasca, Member of National Bank of Greece, where he is responsible for the Internet Banking project and coordinates other projects related to security applications and new technologies to be implemented in the banking area. Filip Cherecheş-Toşa is a web developer with a firm belief in the future of web-based software. He started his career at the age of 9, when he first got a Commodore 64 with tape-drive. Back home in Romania, Filip runs a web development company named eXigo www.exigo.ro, which is actively involved in web-based application development and web design. He is currently a student at the University of Oradea, studying Computer Science, and also an active member of the Romanian PHP Community www.phpromania.net. Mihai Bucica started programming and competing in programming contests (winning many of them), all at age twelve. With a bachelor's degree in computer science from the Automatic Control and Computers Faculty of the Politehnica University of Bucharest, Romania, Bucica works on building communication software with various electronic markets. Even after working with a multitude of languages and technologies, Bucica's programming language of choice remains C++, and he loves the LGPL word. Mihai also co-authored Beginning PHP 5 and MySQL E-Commerce and he can be contacted through his personal website, www.valentinbucica.ro. About the Reviewers Emilian Balanescu is a programmer experienced in many technologies, including PHP, Java, .NET, PostgreSQL, MS SQL Server, MySQL, and others. He currently works as a Wireless Network Administrator at accessNET International S.A. Romania, a company that provides fixed wireless access services operating a point-to-multipoint digital radio communication network with national coverage. His latest project in this position was developing an AJAX-enabled real-time Network Management System (using SNMP, Perl, PHP, and PostgreSQL) used for remote debugging, monitoring system performance, and isolating and troubleshooting system problems. You can reach Emilian at http://www.emilianbalanescu.ro. Paula Badascu is in the third year of studies at Politehnica University of Bucharest, one of the most famous technical universities in Romania, studying Electronics, Telecommunications, and Information Technology. Paula is currently working as an analyst/programmer for NCH Advisors Romania, building web applications using UML, OOP, PHP, SQL, JavaScript, and CSS. She contributed decisively to the analysis and development of a framework used for tracking and monitoring the Romanian capital market. Table of Contents Preface 1 Chapter 1: AJAX and the Future of Web Applications 7 Delivering Functionality via the Web 8 Advantages of Web Applications 9 Building Websites Since 1990 10 HTTP and HTML 10 PHP and Other Server-Side Technologies 11 JavaScript and Other Client-Side Technologies 12 What's Been Missing? 13 Understanding AJAX 14 Building a Simple Application with AJAX and PHP 18 Time for Action—Quickstart AJAX 21 Summary 28 Chapter 2: Client-Side Techniques with Smarter JavaScript 29 JavaScript and the Document Object Model 30 Time for Action—Playing with JavaScript and the DOM 32 JavaScript Events and the DOM 33 Time for Action—Using JavaScript Events and the DOM 35 Even More DOM 37 Time for Action—Even More DOM 37 JavaScript, DOM, and CSS 39 Time for Action—Working with CSS and JavaScript 39 Using the XMLHttpRequest Object 42 Creating the XMLHttpRequest Object 43 Creating Better Objects for Internet Explorer 45 Initiating Server Requests Using XMLHttpRequest 46 Handling Server Response 49 Time for Action—Making Asynchronous Calls with XMLHttpRequest 50 Table of Contents Working with XML Structures 55 Time for Action—Making Asynchronous Calls with XMLHttpRequest and XML 55 Handling More Errors and Throwing Exceptions 59 Creating XML Structures 63 Summary 64 Chapter 3: Server-Side Techniques with PHP and MySQL 65 PHP and DOM 65 Time for Action—Doing AJAX with PHP 66 Passing Parameters and Handling PHP Errors 71 Time for Action—Passing PHP Parameters and Error Handling 72 Connecting to Remote Servers and JavaScript Security 79 Time for Action—Connecting to Remote Servers 81 Using a Proxy Server Script 85 Time for Action—Using a Proxy Server Script to Access Remote Servers 86 A Framework for Making Repetitive Asynchronous Requests 91 Time for Action—Implementing Repetitive Tasks 93 Working with MySQL 101 Creating Database Tables 101 Manipulating Data 104 Connecting to Your Database and Executing Queries 105 Time for Action—Working with PHP and MySQL 106 Wrapping Things Up and Laying Out the Structure 109 Time for Action—Building the Friendly Application 112 Summary 119 Chapter 4: AJAX Form Validation 121 Implementing AJAX Form Validation 122 Thread-Safe AJAX 125 Time for Action—AJAX Form Validation 126 Summary 144 Chapter 5: AJAX Chat 145 Introducing AJAX Chat 145 Implementing AJAX Chat 147 Time for Action—Ajax Chat 148 Summary 164 ii [...]... Contents Chapter 6: AJAX Suggest and Autocomplete Introducing AJAX Suggest and Autocomplete Google Suggest Implementing AJAX Suggest and Autocomplete Time for Action AJAX Suggest and Autocomplete Summary Chapter 7: AJAX Real-Time Charting with SVG Implementing a Real-Time Chart with AJAX and SVG Time for Action Building the Real-Time SVG Chart Summary Chapter 8: AJAX Grid Implementing the AJAX Grid Using... about AJAX, containing loads of very useful links • http://ajaxpatterns.org is about reusable AJAX design patterns • http://www.ajaxinfo.com is a resource of AJAX articles and links • http://dev.fiaminga.com contains many links to various AJAX resources and tutorials 17 AJAX and the Future of Web Applications • http://ajaxguru.blogspot.com • http://www.sitepoint.com/article/remote-scripting -ajax is... advantages over desktop applications • Web applications are easy and inexpensive to deliver With web applications, a company can reduce the costs of the IT department that is in charge of installing the software on the users' machines With web applications, all that users need is a computer with a working web browser and an Internet or intranet connection • Web applications are easy and inexpensive to upgrade... Action AJAX Grid Summary Chapter 9: AJAX RSS Reader Working with RSS The RSS Document Structure Google Reader Implementing the AJAX RSS Reader Time for Action Building the RSS Reader Application Summary Chapter 10: AJAX Drag and Drop Using Drag and Drop on the Web Shopping Carts Sortable Lists Building the AJAX Drag -and- Drop Sortable List Application Time for Action—Task Management Application with AJAX. .. technologies have been developed (and are still being developed) to add flashy lights, accessibility, and power to web applications Notable examples include Java applets and Macromedia Flash, which require the users to install separate libraries into their web browsers Delivering Functionality via the Web Web applications are applications whose functionality is processed on a web server, and is delivered to the... as desktop applications Building user-friendly software has always been easier with desktop applications than with web applications, simply because the Web was designed as a means for delivering text and images, and not complex functionality This problem has gotten significantly more painful in the last few years, when more and more software services and functionality are delivered via the Web Consequently,... potential data synchronization operations and lower security risks In this book we'll further investigate how to use modern web technologies to build better web applications, to make the most out of the possibilities offered by the Web But before getting into the details, let's take a short history lesson 9 AJAX and the Future of Web Applications Building Websites Since 1990 Although the history of... 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... first AJAX program, here are a number of links that may help you in your journey into the exciting world of AJAX: • • http://ajaxblog.com is an AJAX dedicated blog http://www.fiftyfoureleven.com/resources/programming/xmlhttprequest is a comprehensive article collection about AJAX • • http://www.ajaxian.com is the AJAX website of Ben Galbraith and Dion Almaer, the authors of Pragmatic AJAX http://www.ajaxmatters.com... your PHP web applications We hope you'll find this book useful and relevant to your projects For the latest details and updates regarding this book, please visit its mini-site at http://ajaxphp.packtpub.com The book's mini-site also contains additional free chapters and resources, which we recommend you check out when you have the time Preface What This Book Covers Chapter 1: AJAX and the Future of Web . AJAX and PHP Building Responsive Web Applications Enhance the user experience of your PHP website using AJAX with this practical tutorial featuring. scenarios. In AJAX and PHP: Building Responsive Web Applications, we took a pragmatic and safe approach by teaching relevant patterns and best practices that we think any web developer will. for Action—Doing AJAX with PHP 66 Passing Parameters and Handling PHP Errors 71 Time for Action—Passing PHP Parameters and Error Handling 72 Connecting to Remote Servers and JavaScript Security