PHP – AJAX and MySQL

<html>
<head>
<script type=”text/javascript”>
function showUser(str)
{
if (str==””)
{
document.getElementById(“txtHint”).innerHTML=””;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(“txtHint”).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”getuser.php?q=”+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<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>
</select>
</form>
<br />
<div id=”txtHint”><b>Person info will be listed here.</b></div>

</body>
</html

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:

<?php
$q=$_GET[“q”];

$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′>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>specialization</th>
<th>company</th>
<th>Job</th>
</tr>”;

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>”;

mysql_close($con);
?>

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

PHP Development
Advertisements

One thought on “PHP – AJAX and MySQL

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s