Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP - AJAX with PHP

PHP - AJAX with PHP


AJAX (Asynchronous JavaScript and XML) is a technique for exchanging data with the server without refreshing the entire page.

AJAX is a technique that can update parts of a web page without reloading the entire page; it exchanges data with the server in the background and can update parts of the web page content.

AJAX allows a web page to dynamically update parts of its content, providing a faster user experience.

AJAX typically uses the XMLHttpRequest object to communicate with the server in the background, although it can also use modern methods such as the fetch API.

For more information, refer to:AJAX Tutorial

How AJAX Works

Steps for Using AJAX in PHP

**1. Frontend:** JavaScript initiates the AJAX request.

Use XMLHttpRequest or fetch to send a request to the PHP server.

**2. Backend:** PHP receives and processes the request.

PHP obtains the data from the AJAX request and returns the result.

**3. Frontend:** Process the data returned by PHP.

Use JavaScript to parse and display the response data received from PHP.

Using AJAX in PHP

1. Create HTML and JavaScript: First, you need an HTML page and JavaScript code to send the AJAX request.

Example

   

   

<p>AJAX Example</p>

   

   

   

**2. Write the PHP script:** On the server side, you need a PHP file to handle the request and return data.

Example

**3. Send the request:** When the user clicks the button, the JavaScript function sendRequest is called, which creates an XMLHttpRequest object and sends the request to the server.

**4. Handle the response:** After the server processes the request, it returns the result to the client. The client-side JavaScript code checks the response status and updates the page content when the status is 200 (i.e., the request succeeded).


AJAX PHP Example

The example below demonstrates how a web page communicates with a web server when the user types characters in an input box:

Example

Try typing a name in the input box, e.g.: Anna:

Return value:


Example Explanation - HTML Page

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

Example

Enter a name in the input box:

Name:

Return value:

Source code explanation:

If the input box is empty (str.length==0), the function clears the content of the txtHint placeholder and exits the function.

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

The server page called via JavaScript above is a PHP file named "gethint.php".

The source code in "gethint.php" checks the name array, then returns the corresponding names to the browser:

Example

0 if ( strlen ( $q ) > 0 ) {         $hint = "" ;         for ( $i = 0 ; $i < count ( $a ) ; $i ++ ) { if ( strtolower ( $q ) == strtolower ( substr ( $a [ $i ] , 0 , strlen ( $q ) ) ) ) { if ( $hint == "" ) { $hint = $a [ $i ] ; } else { $hint = $hint . " , " . $a [ $i ] ; } } } } // if no match is found, set the output to "no suggestion" if ( $hint == "" ) { $response = "no suggestion" ; } else { $response = $hint ; } // output the return value echo $response ; ?>

Explanation: If JavaScript sends any text (i.e., strlen($q) > 0), the following happens:

  1. Find the name matching the characters sent by JavaScript
  2. If no match is found, set the response string to "no suggestion"
  3. If one or more matching names are found, set the response string with all the names
  4. Send the response to the "txtHint" placeholder

Implementing AJAX with fetch and PHP

HTML + JavaScript:

Example

   

   

   

<p>AJAX with PHP Example</p>

AJAX Example

PHP server (server.php):

Example

'Hello from PHP server!' ) ; } else { $response = array ( 'response' => 'Invalid message' ) ; } // return the result to the client echo json_encode ( $response ) ; ?>

Explanation:

  1. Frontend: When the user clicks the button, JavaScript uses fetch() to send a POST request to server.php, and sends a piece of JSON data.
  2. Backend: The PHP server reads the request sent by the client, processes it, and returns a JSON response.
  3. Response Handling: After JavaScript receives the response from the PHP server, it updates the page content.

PHP AJAX Cross-Origin Problem Solution

If your asynchronous request needs to cross domains, you can check:PHP AJAX Cross-Origin Problem Solution.