Latest web development tutorials

PHP and MySQL instance AJAX

AJAX can be used for interactive communication with the database.

AJAX database instance

The following examples will demonstrate how a web page via AJAX read information from the database:



Examples explain - MySQL database

In the example above, we use the database table is as follows:

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

Examples explain - HTML page

When a user in the above drop-down list, select a user, would execute named "showUser ()" function. This function by the "onchange" event is triggered:

function showUser(str)
	if (str=="")
	if (window.XMLHttpRequest)
		// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
		xmlhttp=new XMLHttpRequest();
		// IE6, IE5 浏览器执行代码
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		if (xmlhttp.readyState==4 && xmlhttp.status==200)

<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
<div id="txtHint"><b>Person info will be listed here.</b></div>


showUser () function performs the following steps:

  • Check whether the user is selected
  • Create XMLHttpRequest object
  • Create function when the server is ready to perform the response
  • File on the server to send requests
  • Please note added to the end of the URL parameter (q) (contains the contents of the drop-down list)

PHP File

The above servers through JavaScript calling this page is called "getuser.php" PHP file.

The source code will run "getuser.php" in once for MySQL database query and returns the results in an HTML table:


$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con)
	die('Could not connect: ' . mysqli_error($con));

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysqli_query($con,$sql);

echo "<table border='1'>

while($row = mysqli_fetch_array($result))
	echo "<tr>";
	echo "<td>" . $row['FirstName'] . "</td>";
	echo "<td>" . $row['LastName'] . "</td>";
	echo "<td>" . $row['Age'] . "</td>";
	echo "<td>" . $row['Hometown'] . "</td>";
	echo "<td>" . $row['Job'] . "</td>";
	echo "</tr>";
echo "</table>";


Explanation: When a query is sent from JavaScript to PHP file will occur:

  1. PHP opens a connection to the MySQL database
  2. Find the selected users
  3. Create HTML table, filling the data and sends back "txtHint" placeholder