Hướng dẫn dùng ajax w3schools trong PHP


AJAX is used to create more interactive applications.


AJAX PHP Example

The following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field:

Example

Start typing a name in the input field below:

Suggestions:


Example Explained

In the example above, when a user types a character in the input field, a function called "showHint()" is executed.

The function is triggered by the onkeyup event.

Here is the HTML code:

Example





Start typing a name in the input field below:



 
 

Suggestions:



Run example »

Code explanation:

First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function.

However, if the input field is not empty, do the following:

  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a PHP file (gethint.php) on the server
  • Notice that q parameter is added to the url (gethint.php?q="+str)
  • And the str variable holds the content of the input field


The PHP File - "gethint.php"

The PHP file checks an array of names, and returns the corresponding name(s) to the browser:

// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

// get the q parameter from URL
$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""
if ($q !== "") {
  $q = strtolower($q);
  $len=strlen($q);
  foreach($a as $name) {
    if (stristr($q, substr($name, 0, $len))) {
      if ($hint === "") {
        $hint = $name;
      } else {
        $hint .= ", $name";
      }
    }
  }
}

// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>




AJAX can be used for interactive communication with a database.


AJAX Database Example

The following example will demonstrate how a web page can fetch information from a database with AJAX:

Example

Person info will be listed here...


Example Explained - The MySQL Database

The database table we use in the example above looks like this:

idFirstNameLastNameAgeHometownJob
1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot

Example Explained

In the example above, when a user selects a person in the dropdown list above, a function called "showUser()" is executed.

The function is triggered by the onchange event.

Here is the HTML code:

Example










Person info will be listed here...


Run example »

Code explanation:

First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint and exit the function. If a person is selected, do the following:

  • 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:






$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123');
if (!$con) {
  die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "








";
while($row = mysqli_fetch_array($result)) {
  echo "";
  echo "";
  echo "";
  echo "";
  echo "";
  echo "";
  echo "";
}
echo "
Firstname Lastname Age Hometown Job
" . $row['FirstName'] . "" . $row['LastName'] . "" . $row['Age'] . "" . $row['Hometown'] . "" . $row['Job'] . "
";
mysqli_close($con);
?>

Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:

  1. PHP opens a connection to a MySQL server
  2. The correct person is found
  3. An HTML table is created, filled with data, and sent back to the "txtHint" placeholder