English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this chapter, we will demonstrate how to send AJAX requests to a PHP file and how to retrieve the content of the PHP file.
The following example shows how the web page communicates with the network server and retrieves the content of the PHP file:
In the above example, the event fetchDoc() triggers a function onclick.
This is the HTML code:
<button type="button" onclick="fetchDoc()">Fetch Content</button> <div id="output"></div> <script> function fetchDoc() { var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { document.getElementById("output").innerHTML = this.responseText; } }); httpRequest.open("GET", "ajax_time.php", true); httpRequest.send(); } </script>
This is the PHP code (ajax_time.php):
<?php echo date("d/m/Y, h:i:s A); ?>
The following example shows how the web page communicates with the web server when the user types a character in the input field:
Start typing a country in the input field below/Region Name:
Country:
Suggestions and Feedback:
In the above example, when the user types a character in the input field, the event showHint() will trigger the onkeyup function.
This is the HTML code:
<!DOCTYPE html> <html> <div> <p>Start typing a country in the input field below/Region Name:/p> <p>Country: <input type="text" onkeyup="showHint(this.value)">/p> <p>Recommendation: <span id="result"></span></p> </div> <script> var elem = document.getElementById("result"); function showHint(name) { if (name.length === 0) {}} elem.innerHTML = ""; return; } else { var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { elem.innerHTML = this.responseText; } }); httpRequest.open("GET", "ajax_hint.php?q=" + name, true); httpRequest.send(); } } </script> </html>
This is PHP code (ajax_hint.php):
<?php // Array of country names $countries = array("Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",...); // Get q parameter from URL $q = $_REQUEST["q"]; $hint = ""; // If $q is different from the hints in the array, then loop through all the hints in the array "" if ($q !== "") { $q = strtolower($q); $len = strlen($q); foreach ($countries as $name) { if (stristr($q, substr($name, 0, $len))) { if ($hint === "") { $hint = $name; } else { $hint .= ", $name"; } } } } //If no hint is found or the correct value is output, then output "no suggestion" echo $hint === "" ? "no suggestion" : $hint; ?>
For a complete list of country names, please seehttps://gist.github.com/DHS/1340150