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
- Send the request: The user triggers an AJAX request through some action (such as clicking a button).
- Create the request: JavaScript creates an XMLHttpRequest object used to communicate with the server.
- Send the request: Send the request to the server via the XMLHttpRequest object.
- Server processing: After the server receives the request, it processes the data.
- Return the response: The server returns the processing result to the client.
- Update the page: After JavaScript receives the server's response, it updates the corresponding part of the web page.
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
AJAX Example
**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:
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:
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send a request to the file on the server
- Note the parameter (q) appended to the end of the URL (containing the input box content)
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:
- Find the name matching the characters sent by JavaScript
- If no match is found, set the response string to "no suggestion"
- If one or more matching names are found, set the response string with all the names
- Send the response to the "txtHint" placeholder
Implementing AJAX with fetch and PHP
HTML + JavaScript:
Example
AJAX with PHP Example
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:
- Frontend: When the user clicks the button, JavaScript uses
fetch()to send a POST request toserver.php, and sends a piece of JSON data. - Backend: The PHP server reads the request sent by the client, processes it, and returns a JSON response.
- 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.