Thursday, August 11, 2011

PHP - AJAX and MySQL

AJAX can be used for interactive communication with a database.

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:












Person info will be listed here.



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 "getuser.php".

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

";

while($row = mysql_fetch_array($result))
{
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
}
echo "