Database-enabled Ajax with PHP | WebReference

Database-enabled Ajax with PHP

Database-enabled Ajax with PHP

By Kris Hadlock

Ajax has taken the Web to a new level by offering an intuitive interactive model that rivals the desktop. To compete with desktop applications, database interaction is necessary to unleash the true power of an Ajax Web application.

In this article you'll learn how to create database-enabled Ajax requests using PHP and MySQL. We begin by creating the front-end HTML and JavaScript files used to make requests to the server-side. The requested server-side is a PHP file which bridges the gap between Ajax and a PHP object that connects to a MySQL database and returns results as an XML response to the Ajax engine. To cover this functionality you'll learn about the concepts from a high level overview rather than focusing on each and every line of code. The complete source code for this sample can be downloaded and is necessary to create a working sample on your personal server. Let's get started by taking a look at the front-end.

The Front-end

The front-end of this project consists of an HTML file and two JavaScript objects. The HTML includes the JavaScript and represents user postings. The user postings could represent anything, such as to-do lists, notes and so on.

The two JavaScript objects are called Ajax and Page. The Ajax object is the engine we use to make all the requests to the server and delegate the responses to the appropriate callback methods.

The Page object handles rendering of posts that are returned from the database and provides the user with a way to edit and delete existing postings or add new ones. The most important method in this object is the onResponse method, which is the callback method for all Ajax requests. It handles parsing the XML and rendering it as HTML.

The onResponse method iterates the postings from the XML file and creates two representations of the data. The first is a nicely styled title, paragraph and date; the second is a form, which allows you to edit, delete and add new information to a posting. While the onResponse method renders both, it hides one based on the mode that the user is currently in. For instance, if the user is in edit mode, the form is visible and vice versa. This produces a toggle effect between the different states of an individual posting. In order to create this toggle effect we have a method, which handles this called toggle. The other methods of interest in the Page object are saveNewPost, deletePost and getPost. Each of these methods makes requests to the server-side through the Ajax object to accomplish a specific goal, such as saving, deleting or getting a post. Take a look at the source code from the sample download to see the inner workings of each method.

Created: March 27, 2003
Revised: November 23, 2006

URL: https://webreference.com/programming/javascript/kh/1