<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″>PHP Developer</option>
<option value=”2″>Magennto Developer</option>
<option value=”3″>Joomla Developer</option>
<option value=”4″>WordPress Developer</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
  • Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File

The page on the server called by the JavaScript above is a PHP file called “getdeveloper.php”.

The source code in “getdeveloper.php” runs a query against a MySQL database, and returns the result in an HTML table:


$con = mysql_connect(‘localhost’, ‘mconnect’, ‘mconnect123’);
if (!$con)
die(‘Could not connect: ‘ . mysql_error());

mysql_select_db(“mconnect_a_php”, $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[‘specialization’] . “</td>”;
echo “<td>” . $row[‘company’] . “</td>”;
echo “<td>” . $row[‘Job’] . “</td>”;
echo “</tr>”;
echo “</table>”;


All Done, now try the same code with your application.

PHP Development

One thought on “PHP – AJAX and MySQL

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s