Hướng dẫn dùng ajax w3schools trong PHP
AJAX is used to create more interactive applications. Show AJAX PHP ExampleThe following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field: ExampleStart typing a name in the input field below: Suggestions: Example ExplainedIn 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: ExampleStart 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:
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 // get the q parameter from URL $hint = ""; // lookup all
hints from array if $q is different from "" // Output "no suggestion" if no hint was found or output correct values AJAX can be used for interactive communication with a database. AJAX Database ExampleThe following example will demonstrate how a web page can fetch information from a database with AJAX: ExamplePerson info will be listed here... Example Explained - The MySQL DatabaseThe database table we use in the example above looks like this:
Example ExplainedIn 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: ExamplePerson 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:
The PHP FileThe 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'); mysqli_select_db($con,"ajax_demo"); echo "
mysqli_close($con); ?> Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:
|