AJAX database
The following example will demonstrate how a web page can fetch information from a database with AJAX technology.
The MySQL Database
The database table we use in this example looks like this:
| id | FirstName | LastName | Age | Hometown | Job |
|---|---|---|---|---|---|
| 1 | Peter | Griffin | 41 | Quahog | Brewery |
| 2 | Lois | Griffin | 40 | Newport | Piano Teacher |
| 3 | Joseph | Swanson | 39 | Quahog | Police Officer |
| 4 | Glenn | Quagmire | 41 | Quahog | Pilot |
The HTML page
The HTML page contains a link to an external JavaScript, an HTML form, and a div element:
As you can see it is just a simple HTML form with a drop down box called "customers".
The below the form will be used as a placeholder for info retrieved from the web server.
When the user selects data, a function called "showUser()" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showUser() is called.
The JavaScript code
This is the JavaScript code stored in the file "selectuser.js":
The stateChanged() and GetXmlHttpObject functions are the same as in the PHP AJAX Suggest chapter, you can go to there for an explanation of those.
The showUser() Function
When a person in the drop-down box is selected, the showUser() function executes the following:
- Calls the GetXmlHttpObject() function to create an XMLHTTP object
- Defines an URL (filename) to send to the server
- Adds a parameter (q) to the URL with the content of the drop-down box
- Adds a random number to prevent the server from using a cached file
- Each time the readyState property changes, the stateChanged() function will be executed
- Opens the XMLHTTP object with the given URL
- Sends an HTTP request to the server
The PHP Page
The PHP page called by the JavaScript, is called "getuser.php".
The PHP script runs an SQL query against a MySQL database, and returns the result as HTML:
When the query is sent from the JavaScript to the PHP page, the following happens:
- PHP opens a connection to a MySQL server
- The correct person is found
- An HTML table is created, and filled with data, and sent back to the "txtHint" placeholder
No comments:
Post a Comment