« Previous Chapter Next Chapter »

AJAX can be used for interactive communication with a database.

AJAX Database Example

The Below example will demonstrate how a web page can fetch information from a database with AJAX:


Person info will be listed here...

Example Explained - The MySQL Database

The database table we use in the example above looks like this:

id FirstName LastName Age Hometown Job
1 William Dharsan 41 Los Angels Sprinter
2 Adheem Dharsan 40 Tamilnadu Programmer
3 Joseph Swanson 39 Los Angels Designer
4 Glenn Boopathi 41 Los Angels Cop

Example Explained - The HTML Page

When a user selects a user in the dropdown list above, a function called "showUser()" is executed. The function is triggered by the "onchange" event:

<script type="text/javascript">
function showUser(str)
if (str=="")
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  {// code for 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">William Dharsan</option>
<option value="2">Adheem Dharsan</option>
<option value="3">Glenn Boopathi</option>
<option value="4">Joseph Swanson</option>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>


The showUser() function does the following:

  • Check if a person is selected
  • 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
  • Note: a parameter (q) is added to the URL (with Content of the dropdown list)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "getuser.html".

The source code in "getuser.html" runs a query against a MySQL database, and returns the result in an HTML table:


$con = mysql_connect('localhost', 'William', 'password');
if (!$con)
  die('Could not connect: ' . mysql_error());

mysql_select_db("ajax_demo", $con);

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

$result = mysql_query($sql);

echo "<table border='1'>

while($row = mysql_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 the query is sent from the JavaScript to the PHP file, the following happens:

  1. PHP opens a connection to a MySQL server
  2. The correct person is found
  3. An HTML table is created, filled with data, and sent back to the "txtHint" placeholder

« Previous Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!