AJAX database
PHP - AJAX and MySQL
AJAX can be used to communicate interactively with the database.
AJAX Database Example
The following example will demonstrate how a web page reads information from the database through AJAX:
Example
Select a person: Peter Griffin Lois Griffin Joseph Swanson Glenn Quagmire
Select the corresponding option, the user information will be displayed here...
Example explanation - MySQL database
In the above example, the database table we use is as follows:
Example explanation - HTML page
When the user selects in the drop-down list above When a user is selected, a function named "showUser()" will be executed. This function is triggered by the "onchange" event:
showUser() function performs the following steps:
1) Check if a user is selected
2) Create an XMLHttpRequest object
3) Create a function that executes when the server response is ready
4) Send a request to a file on the server
5) Please note the parameters added to the end of the URL (q ) (Contains the contents of the drop-down list)
PHP file
The server page called above through JavaScript is named "getuser.php " PHP file.
The source code in "getuser.php" will run a query against the MySQL database and return the results in an HTML table:
"; while($row = mysqli_fetch_array($result)) { echo " Firstname Lastname Age Hometown Job "; echo " "; } echo ""; mysqli_close($con); ?>" . $row['FirstName'] . " "; echo "" . $row['LastName'] . " "; echo "" . $row['Age'] . " "; echo "" . $row['Hometown'] . " "; echo "" . $row['Job'] . " "; echo "
Explanation:When the query starts from When JavaScript is sent to a PHP file, what happens is:
1. PHP opens a connection to the MySQL database
2. Finds the selected user
3. Creates the HTML table, Fill in the data and send back the "txtHint" placeholder