PHP β AJAX and PHP
AJAX (Asynchronous JavaScript and XML) is a technology used to exchange data with a server without refreshing the entire page.
AJAX is a technique that allows parts of a web page to be updated without requiring a full page reload. It works by exchanging data with the server in the background and can update specific parts of the web page content.
AJAX allows web pages to dynamically update partial 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 Request: The user triggers an AJAX request through some action (such as clicking a button).
- Create Request: JavaScript creates an XMLHttpRequest object to communicate with the server.
- Send Request: The request is sent to the server via the XMLHttpRequest object.
- Server Processing: The server receives the request and processes the data.
- Return Response: The server returns the processing result to the client.
- Update Page: After receiving the server's response, JavaScript updates the corresponding part of the web page.
Steps for Using AJAX in PHP
1. Front-end: JavaScript initiates an AJAX request.
Use XMLHttpRequest or fetch to send a request to the PHP server.
2. Back-end: PHP receives and processes the request.
PHP retrieves the data from the AJAX request and returns the result.
3. Front-end: 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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAX Example</title>
<script>
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.open("GET", "your_php_file.php?param=value", true);
xhr.send();
}
</script>
</head>
<body>
<button onclick="sendRequest()">Send AJAX Request</button>
<div id="result"></div>
</body>
</html>
2. Write the PHP Script: On the server side, you need a PHP file to process the request and return data.
Example
<?php
if(isset($_GET['param'])){
// Process request parameters
$param=$_GET['param'];
// Perform some operations...
// Return response
echo "Received parameter: ".$param;
}
?>
3. Send Request: When the user clicks the button, the JavaScript function sendRequest is called, which creates an XMLHttpRequest object and sends a request to the server.
4. Handle 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 was successful).
AJAX PHP Example
The following example demonstrates how a web page communicates with a web server when a user types characters in an input field:
Example
Try typing a name in the input field, such as: Anna:
Return value:
Example Explanation - HTML Page
When the user types characters in the input field above, the "showHint()" function is executed. This function is triggered by the "onkeyup" event:
Example
<html>
<head>
<script>
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
// Code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// Code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>Enter a name in the input field:</b></p>
<form>
Name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Return value: <span id="txtHint"></span></p>
</body>
</html>
Source code explanation:
If the input field is empty (str.length==0), the function clears the content of the txtHint placeholder and exits the function.
If the input field is not empty, showHint() executes the following steps:
- Create an XMLHttpRequest object
- Create a function to execute when the server response is ready
- Send a request to a file on the server
- Note the parameter (q) appended to the end of the URL (containing the input field content)
The server page called via the JavaScript above is a PHP file named "gethint.php".
The source code in "gethint.php" checks an array of names and returns the corresponding names to the browser:
Example
<?php
// Fill the array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
// Get the q parameter from the URL
$q=$_GET;
// Check if there is a match, if q > 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];
}
}
}
}
// Set output to "no suggestion" if no match is found
if($hint=="")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
// Output the response
echo $response;
?>
Explanation: If JavaScript sends any text (i.e., strlen($q) > 0), the following occurs:
- Search for names 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 names
- Send the response to the "txtHint" placeholder
Using fetch and PHP for AJAX
HTML + JavaScript:
Example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX with PHP Example</title>
</head>
<body>
<h1>AJAX Example</h1>
<button id="ajaxButton">Get Data from PHP</button>
<div id="result"></div>
<script>
document.getElementById('ajaxButton').addEventListener('click', function() {
// Send AJAX request
fetch('server.php', {
method: 'POST', // Use POST request
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message: "Hello from client" })
})
.then(response => response.json()) // Parse as JSON
.then(data => {
document.getElementById('result').innerHTML = data.response; // Update page
})
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>
PHP Server (server.php):
Example
<?php
// Set response header to support JSON
header('Content-Type: application/json');
// Get input data from AJAX request
$request=json_decode(file_get_contents("php://input"),true);
// Process data and return response
if($request['message']==="Hello from client"){
$response=array('response'=>'Hello from PHP server!');
}else{
$response=array('response'=>'Invalid message');
}
// Return the result to the client
echo json_encode($response);
?>
Explanation:
- Front-end: When the user clicks the button, JavaScript uses
fetch()to send a POST request toserver.phpwith some JSON data. - Back-end: The PHP server reads the request sent by the client, processes it, and returns a JSON response.
- Response Handling: After receiving the response from the PHP server, JavaScript updates the page content.
PHP AJAX Cross-Domain Problem Solution
If your asynchronous request needs to handle cross-domain issues, you can check: PHP AJAX Cross-Domain Problem Solution.
YouTip