PHP - AJAX and MySQL
AJAX can be used to communicate with a database interactively.
AJAX Database Example
The following example demonstrates how a web page can read information from a database via AJAX:
SQL file for the Websites table used in this tutorial:websites.sql。
Example
Example Explained - MySQL Database
In the above example, the database table we use is shown below:
mysql> select * from websites; +----+--------------+---------------------------+-------+---------+ | id | name | url | alexa | country | +----+--------------+---------------------------+-------+---------+ | 1 | Google | https://www.google.cm/ | 1 | USA | | 2 | 淘宝 | https://www.taobao.com/ | 13 | CN | | 3 | Example | http://www.example.com/ | 4689 | CN | | 4 | 微博 | http://weibo.com/ | 20 | CN | | 5 | Facebook | https://www.facebook.com/ | 3 | USA | +----+--------------+---------------------------+-------+---------+ 5 rows in set (0.01 sec)
Example Explained - HTML Page
When the user selects a website in the dropdown list above, a function called "showSite()" is executed. The function is triggered by the "onchange" event:
test.html file code:
The showSite() function performs the following steps:
- Check if a website is selected
- Create an XMLHttpRequest object
- Create a function to execute when the server response is ready
- Send a request to a file on the server
- Note that a parameter (q) is added to the end of the URL (containing the content of the dropdown list)
PHP File
The server page called via JavaScript above is a PHP file named "getsite_mysql.php".
The source code in "getsite_mysql.php" runs a query against a MySQL database and returns the result in an HTML table:
getsite_mysql.php file code:
Explanation: When the query is sent from JavaScript to the PHP file, the following happens:
- PHP opens a connection to a MySQL database
- Find the selected website
- Creates an HTML table, fills it with data, and sends it back to the "txtHint" placeholder