PHP development basic tutorial AJAX and PHP

AJAX and PHP examples

Summary in one sentence: AJAX is used to create more interactive applications

The following example will demonstrate how the web page communicates with the Web server when the user types characters in the input box:

The page effect is shown in the picture on the right


Explanation of examples - HTML page

When the user types characters in the input box above, the "showHint()" function will be executed. This function is triggered by the "onkeyup" event:

Note: the onkeyup event will occur when the keyboard key is released

The specific code is as follows

     

在输入框中输入一个姓名

姓名:

返回值:

Source code explanation :

If the input box is empty (str.length==0), this function will clear the content of the txtHint placeholder and exit the function.

If the input box is not empty, then showHint() will perform the following steps:

Create an XMLHttpRequest object

Create a function that is executed when the server response is ready

Send a request to the file on the server

Please pay attention to the parameter (q) added to the end of the URL (contains the content of the input box)


Explanation of examples - PHP file

The server page called above through JavaScript is a PHP file named "2.php".

The source code in "2.php" will check the name array and then return the corresponding name to the browser. The code is as follows:

0 if (strlen($q) > 0) { $hint=""; for($i=0; $i

Explanation:

If JavaScript sends any text (i.e. strlen($q) > 0), what happens is:

Find names matching the characters sent by JavaScript

If no match is found, Then set the response string to "no suggestion"

If one or more matching names are found, set the response string with all names

Send the response to the "txtHint" placeholder


#Learning experience

This example mainly includes the following knowledge points:

  • Form basics

  • Onkeyup event: when the keyboard key is released Occurrence

  • Function call, function value passing

  • Creation of AJAX XMLHttpRequest object, function executed when the server responds, transfer to the server File sending request: See 1-5 for learning experience

  • HTML DOM getElementById() method: Returns a reference to the first object with the specified ID

  • Array assignment method

  • Get method form submission

Functions related to strings:

  • strlen()

  • count()

  • Strtolower()

Continuing Learning
||

在输入框中输入一个姓名

姓名:

返回值:

submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!