The JavaScript
This is the JavaScript code stored in the file "Selectuser.js":
var xmlHttp
function Showuser (str)
{
xmlhttp=getxmlhttpobject ()
if (xmlhttp==null)
{
alert ("Browser does Not support HTTP Request "]
return
}
var url=" getuser.php "
url=url+
" q= "+str url=url+" &sid= "+math.random ()
xmlhttp.onreadystatechange=statechanged
xmlhttp.open (" Get ", Url,true)
Xmlhttp.send (null)
}
function statechanged ()
{
if (xmlhttp.readystate==4 | | xmlhttp.readystate== "complete")
{
document.getElementById ("Txthint"). Innerhtml=xmlhttp.responsetext
}
}
function Getxmlhttpobject ()
{
var xmlhttp=null;
Try
{
//Firefox, Opera 8.0+, Safari
xmlhttp=new XMLHttpRequest ();
}
catch (E)
{
//internet Explorer
try
{
xmlhttp=new activexobject ("msxml2.xmlhttp");
}
catch (E)
{
xmlhttp=new activexobject ("Microsoft.XMLHTTP");
}
return xmlHttp;
}
For example to explain
The statechanged () and Getxmlhttpobject functions are the same as PHP's AJAX chapters suggest that you can go there to explain these.
The Showuser () function
If an item chooses to perform in a Drop-down box, the following functions are available:
Call the Getxmlhttpobject function to create a XMLHTTP object
Defines the URL (file) to be transmitted to the server
Add a parameter (Q) to the URL with the contents of the dropdown box
Add a random number to prevent the server from using cache files
When call statechanged changes, it triggers
Opening XMLHTTP objects with specific URLs.
Send an HTTP request to the server
PHP page
The server's page requirements for JavaScript, is a simple php file named "getuser.php".
The page is written in PHP and uses a MySQL database.
The code runs a database of SQL queries and returns the result as an HTML table:
<?php
$q =$_get["Q"];
$con = mysql_connect (' localhost ', ' Peter ', ' abc123 ');
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 ' >
<tr>
<th>Firstname</th>
<th>lastname</ th>
<th>Age</th>
<th>Hometown</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 [' Age ']. "</td>";
echo "<td>". $row [' Hometown ']. "</td>";
echo "<td>". $row [' Job ']. "</td>";
echo "</tr>";
}
echo "</table>";
Mysql_close ($con);
? >
All right, our php+ajax is done.