Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

AJAX and PHP
Nội dung xem thử
Mô tả chi tiết
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
Table of Contents
Chapter 6: AJAX Suggest and Autocomplete 165
Introducing AJAX Suggest and Autocomplete 165
Google Suggest 166
Implementing AJAX Suggest and Autocomplete 167
Time for Action—AJAX Suggest and Autocomplete 168
Summary 188
Chapter 7: AJAX Real-Time Charting with SVG 189
Implementing a Real-Time Chart with AJAX and SVG 190
Time for Action—Building the Real-Time SVG Chart 193
Summary 202
Chapter 8: AJAX Grid 203
Implementing the AJAX Grid Using Client-Side XSLT 204
Time for Action—AJAX Grid 205
Summary 221
Chapter 9: AJAX RSS Reader 223
Working with RSS 223
The RSS Document Structure 224
Google Reader 224
Implementing the AJAX RSS Reader 225
Time for Action—Building the RSS Reader Application 226
Summary 236
Chapter 10: AJAX Drag and Drop 237
Using Drag and Drop on the Web 237
Shopping Carts 237
Sortable Lists 238
Building the AJAX Drag-and-Drop Sortable List Application 238
Time for Action—Task Management Application with AJAX 241
Summary 253
Appendix A: Preparing Your Working Environment 255
Preparing Your Windows Playground 256
Installing Apache 256
Installing MySQL 258
Installing PHP 259
iii
Table of Contents
Preparing Your *nix Playground 261
Installing Apache 261
Installing MySQL 261
Installing PHP 262
Installing phpMyAdmin 263
Preparing the AJAX Database 264
Index 267
iv
Preface
AJAX is a complex phenomenon that means different things to different people. Computer users
appreciate that their favorite websites are now friendlier and feel more responsive. Web
developers learn new skills that empower them to create sleek web applications with little effort.
Indeed, everything sounds good about AJAX!
At its roots, AJAX is a mix of technologies that lets you get rid of the evil page reload, which
represents the dead time when navigating from one page to another. Eliminating page reloads is
just one step away from enabling more complex features into websites, such as real-time data
validation, drag and drop, and other tasks that weren't traditionally associated with web
applications. Although the AJAX ingredients are mature (the XMLHttpRequest object, which is
the heart of AJAX, was created by Microsoft in 1999), their new role in the new wave of web
trends is very young, and we'll witness a number of changes before these technologies will be
properly used to the best benefit of the end users. At the time of writing this book, the "AJAX"
name is about just one year old.
AJAX isn't, of course, the answer to all the Web's problems, as the current hype around it may
suggest. As with any other technology, AJAX can be overused, or used the wrong way. AJAX
also comes with problems of its own: you need to fight with browser inconsistencies,
AJAX-specific pages don't work on browsers without JavaScript, they can't be easily
bookmarked by users, and search engines don't always know how to parse them. Also, not
everyone likes AJAX. While some are developing enterprise architectures using JavaScript,
others prefer not to use it at all. When the hype is over, most will probably agree that the middle
way is the wisest way to go for most 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 need sooner
or later. We teach you how to avoid the common pitfalls, how to write efficient AJAX code, and
how to achieve functionality that is easy to integrate into current and future web applications,
without requiring you to rebuild the whole solution around AJAX. You'll be able to use the
knowledge you learn from this book right away, into 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 Applications is an initial incursion into the world of
AJAX and the vast possibilities it opens up for web developers and companies, to offer a better
experience to their users. In this chapter you'll also build your first AJAX-enabled web page,
which will give you a first look of the component technologies.
Chapter 2: Client-Side Techniques with Smarter JavaScript will guide you through the
technologies you'll use to build AJAX web clients, using JavaScript, the DOM, the XMLHttpRequest
object, and XML. While not being a complete tutorial for these technologies, you'll be put on the
right track for using them together to build a solid foundation for your future applications.
Chapter 3: Server-Side Techniques with PHP and MySQL completes the theoretical foundation by
presenting how to create smart servers to interact with your AJAX client. You'll learn various
techniques for implementing common tasks, including handling basic JavaScript security and
error-handling problems.
Chapter 4: AJAX Form Validation guides you through creating a modern, responsive, and secure
form validation system that implements both real-time AJAX validation and server-side validation
on form submission.
Chapter 5: AJAX Chat presents a simple online chat that works exclusively using AJAX code, without
using Java applets, Flash code, or other specialized libraries as most chat applications do these days.
Chapter 6: AJAX Suggest and Autocomplete builds a Google Suggest-like feature, that helps you
quickly find PHP functions, and forwards you to the official help page for the chosen function.
Chapter 7: AJAX Real-Time Charting with SVG teaches you how to implement a real-time
charting solution with AJAX and SVG. SVG (Scalable Vector Graphics) is a text-based graphics
language that can be used to draw shapes and text.
Chapter 8: AJAX Grid teaches you how to build powerful AJAX-enabled data grids. You'll learn
how to parse XML documents using XSLT to generate the output of your grid.
Chapter 9: AJAX RSS Reader uses the SimpleXML PHP library, XML, and XSLT to build a
simple RSS aggregator.
Chapter 10: AJAX Drag and Drop is a demonstration of using the script.aculo.us framework to
build a simple list of elements with drag-and-drop functionality.
Appendix A: Preparing Your Working Environment teaches you how to install and configure the
required software: Apache, PHP, MySQL, phpMyAdmin. The examples in this book assume that
you have set up your environment and sample database as shown here.
At the book's mini-site at http://ajaxphp.packtpub.com, you can find the online demos for
all the book's AJAX case studies.
2
Preface
What You Need for This Book
To go through the examples of this book you need PHP 5, a web server, and a database server. We
have tested the code under several environments, but mostly with the Apache 2 web server, and
MySQL 4.1 and MySQL 5 databases.
You can choose, however, to use another web server, or another database product, in which case
the procedures presented in the chapters might not be 100% accurate. It is important to have PHP
5 or newer, because we use some features, such as Object Oriented Programming support, which
aren't available in older versions.
Please read Appendix A for more details about setting up your machine. If your machine already
has the required software, you still need to read the final part of Appendix A, where you are
instructed about creating a database that is used for the examples in this book.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of
information. Here are some examples of these styles, and an explanation of their meaning.
There are three styles for code. Code words in text are shown as follows: "We can include other
contexts through the use of the include directive."
A block of code will be set as follows:
// function calls the server using the XMLHttpRequest object
function process()
{
// retrieve the name typed by the user on the form
name = document.getElementById("myName").value;
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, false);
// make synchronous server request
xmlHttp.send(null);
// read the response
handleServerResponse();
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or
items will be made bold:
// function calls the server using the XMLHttpRequest object
function process()
{
// retrieve the name typed by the user on the form
name = document.getElementById("myName").value;
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, false);
// make synchronous server request
xmlHttp.send(null);
// read the response
handleServerResponse();
}
3