AJAX can be used for interactive communication with a database.
AJAX Database Example
The following example will demonstrate how a web page can fetch information from a database with AJAX:
Example Explained – The MySQL Database
The database table we use in the example above looks like this:
In the example above, when a user selects a person in the dropdown list above, a function called “showUser()” is executed.
The function is triggered by the onchange event.
Here is the HTML code:
First, check if person is selected. If no person is selected (str == “”), clear the content of txtHint and exit the function. If a person is selected, do the following:
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send the request off to a file on the server
- Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The PHP File
The source code in “getuser.php” runs a query against a MySQL database, and returns the result in an HTML table:
- PHP opens a connection to a MySQL server
- The correct person is found
- An HTML table is created, filled with data, and sent back to the “txtHint” placeholder