Creating an Ajax Process Using PHP and Oracle
by Larry Ullman
Published February 2007
Use the power of JavaScript to add seamless database interactions to your Web pages.
Downloads for this article:
For some time now, Ajax (Asynchronous JavaScript and XML), has been all the rage in the Web development world. Coming to the forefront with some of Google's features (Suggest, Maps, Gmail, and so on), Ajax performs server requests without the user having to submit a form or click on a link. In other words, the Web browser can make the server request, and handle the response, without the user doing anything or even knowing that this is happening. The immediacy that Ajax brings is not only a great convenience, but it can also be downright cool.
In this recipe, I discuss all the code necessary to use Ajax to go from a simple Web page to a JavaScript function to an XMLHttpRequest to a PHP script and, finally, to an Oracle database. Along with the code, I do talk about the individual pieces with respect to the whole picture: what each chunk does and why it's important. By reading this HowTo, you will acquire not only some sample code but also, hopefully, a broader understanding of the whole Ajax concept.
Background
The example I'll be working with will be a registration form (or a minimal part of it, anyway). The theory is that I must confirm unique email addresses in the users table so that people cannot register multiple times using the same address. This is normally part of the validation process that comes after the user submits the form to the handling PHP script. But why should the user have to wait until then for this piece of validation? Instead, as soon as the user enters their email address and goes to the next form field, the email address will be immediately validated. But to do so, I still need to query the database, which is where Ajax comes in.
The simplified table structure for this example could be created with the following SQL statement (without the presence of the other tables, I've done away with identifying keys and such).
CREATE TABLE users (
email VARCHAR2(60)
)
INSERT INTO users (email) VALUES ('this@that.com')
INSERT INTO users (email) VALUES ('me@school.edu')
INSERT INTO users (email) VALUES ('fake@address.net')
- Create the PHP script that queries the Oracle database.
- Manually test the PHP script to see how it works.
- Write the JavaScript code that interacts with the PHP script.
- Make the HTML form that ties into the JavaScript.
- Test the entire process.
Step 1: Programming the Database Query
The entire PHP script is called ajax.php. (See sample code zip.) The purpose of this script is to run a query in Oracle and print a message based upon the results of the query. This is all very basic Oracle, SQL, and PHP, but I'll run through it to clarify what's happening.
The script expects to receive an email address in the URL, which is available in the variable $_GET['email']. Then the script connects to the Oracle database. The query itself counts how many records in the users table have that email address:
SELECT COUNT(*) AS NUM_ROWS FROM users WHERE email='{$_GET['email']}'
if ($rows > 0) {
echo 'Email address has already been registered!';
} else {
echo 'Email address is available!';
}
If you want to improve this script, you can confirm that the email address matches a regular expression pattern for email addresses. If so, execute the query like normal; if not, echo a statement saying that it's not a valid email address. At the very least, you'd likely want to prevent SQL injection attacks. (I.e., avoid using the $_GET variable in your query without some assurances of its validity.)
Step 2: Testing the PHP Script
Because this entire Ajax process involves several technologies—HTML, JavaScript, PHP, SQL, and Oracle—you'll be best off testing each piece as you go. If you don't, you can easily get lost trying to find where a problem exists. Testing this PHP script should be fairly easy:
- Make sure you've created the table in Oracle and populated it.
- Edit ajax.php so that it uses valid connection parameters for your Oracle installation.
- Save the script as ajax.php.
- Place it in the proper directory for your Web server.
- Go to http://yoururl/ajax.php?email=X in your Web browser.
Step 3: Programming the JavaScript
This section of the process is probably the most difficult unless you've done tons of JavaScript already. In any case, the JavaScript code is the heart of the Ajax process, as it performs and handles the request from the PHP page. I'll go through this code in detail.
The JavaScript code will define three functions. The first creates a request object variable:
function createRequestObject() {
var ro;
if (navigator.appName == "Microsoft Internet Explorer") {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} else {
ro = new XMLHttpRequest();
}
return ro;
}
This function is immediately called by the JavaScript code when the page is first loaded:
var http = createRequestObject();
Next up is the function that calls the PHP script:
function sendRequest(email) {
http.open('get', 'ajax.php?email=' + encodeURIComponent(email));
http.onreadystatechange = handleResponse;
http.send(null);
}
To recap, the first function, createRequestObject(), makes the object variable that's needed. The second function, sendRequest(), makes the actual request of the PHP script. Now we need a function that handles that request:
function handleResponse() {
if (http.readyState == 4) {
document.getElementById('email_label').innerHTML = http.responseText;
}
}
At this point, the JavaScript knows what the result of the PHP script was. All you need to do is get the JavaScript to notify the user of that result. An easy option would be to use an alert() box:
alert(http.responseText);
Whew! Hopefully you followed all that. To repeat, this is the most important and most complex part of this sequence. The JavaScript uses three functions to do three things: define a browser-specific request object; make a request to the PHP script; and, do something with the results of the request. If you're confused by any of this, or when it comes time to make a more complex Ajax application, you'll likely want to do a little research on JavaScript and DOM.
Step 4: Making a JavaScript-functional HTML Form
As I wrote previously, the premise behind this example is a registration form that takes, at the least, an email address. The minimal form would be:<form action="somepage.php" method="post">
Email Address: <input name="email" type="text" size="30" maxlength="60" /><br />
First Name: <input name="first_name" type="text" size="20" maxlength="20" /><br />
(Rest of the form...)
</form>
Two more things are required, though. First, this form must somehow call the JavaScript code that makes the request. You could use several tricks to do that: make a clickable link, wait for the submit button to be clicked, and so on. I've decided that once the user has entered an email address and has gone on to the next form element, the JavaScript should be called. This requires the onchange() method, which I'll add to the email input:
Email Address: <input name="email" type="text" size="30" maxlength="60"
onchange="sendRequest(this.form.email.value)" />
The second thing the HTML form needs is a place where JavaScript can "write" the received message so that it's visible to the user. As the handleResponse() function dictates, that message will be assigned to the innerHTML of an element called email_label. For this I add a span with that ID after the email address input:
<span id="email_label"></span>
Step 5: Testing the Ajax Process
Having completed the HTML and JavaScript, you should save that as ajax.html (or anything, really), then place it in the same directory as the PHP script. Load the form by running it in your Web browser, through a URL, not by opening it from the file system (i.e, go to http://yoururl/ajax.html). Type an unused email address in the proper input, then tab or click on the next input. Repeat using a stored email address.
The two screenshots below show the results you should see. Absolute magic!
Conclusion
In this article you've seen how you can easily implement an Ajax process using PHP and Oracle. By doing so, server side validation is being accomplished within the client (although you should still keep server side validation as well, in case JavaScript is disabled). This particular example, in my opinion, demonstrates a nice feature for an end user, saving them from having to:
- Submit the form
- See that the email address has already been registered
- Return to the form
- Repeat
Also, I think this example and the concept in general is kind of cool. And on the Web, that's not an insignificant factor.
Of course, there's tons more you can do with Ajax, PHP, and Oracle. The example in this article sent only one piece of data to the PHP script and retrieved just a string. You can send much more back and forth. If you have a significant amount of data to be returned to the calling page, you can have PHP return it in XML format, then use JavaScript to parse and display it. If you search online, you'll find many different examples.
Larry Ullman is the Director of Digital Media Technology and Lead Web Developer at
DMC Insights Inc., a company specializing in information technology. Larry lives outside of Washington, D.C., and is also the author of several books on PHP, SQL, Web development, and other computer technologies.