|
Page 2 of 2 Example Explained The stateChanged() and GetXmlHttpObject functions are the same as in the PHP AJAX Suggest chapter, you can go to there for an explanation of those. The showUser() Function If an item in the drop down box is selected the function executes the following: - Calls on the GetXmlHttpObject function to create an XMLHTTP object
- Defines the url (filename) to send to the server
- Adds a parameter (q) to the url with the content of the dropdown box
- Adds a random number to prevent the server from using a cached file
- Call stateChanged when a change is triggered
- Opens the XMLHTTP object with the given url.
- Sends an HTTP request to the server
The PHP Page The server page called by the JavaScript, is a simple PHP file called "getuser.php". The page is written in PHP and uses a MySQL databse. The code runs a SQL query alongside a database 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); ?> Example Explained When the query is sent from the JavaScript to the PHP page the following happens: - PHP opens a connection to a MySQL server
- The "user" with the specified name is found
- A table is created and the data is inserted and sent to the "txtHint" placeholder
<< Start < Prev 1 2 Next > End >> |
|
Last Updated ( Thursday, 03 April 2008 )
|