This topic explains how PHP works with AJAX requests using the $_GET and $_POST superglobal variables to send and receive data without reloading the page.
$_GET reads data from URL parameters$_POST reads data from request bodyJavaScript sends data using XMLHttpRequest. PHP scripts read the incoming values using $_GET or $_POST and respond with output that updates the page dynamically.
// HTML + JavaScript + PHP GET example
<input type="text" id="nameGet">
<button onclick="sendGet()">Send GET</button>
<div id="responseGet"></div>
function sendGet() {
var name=document.getElementById("nameGet").value;
var xhr=new XMLHttpRequest();
xhr.open("GET","get_process.php?name="+encodeURIComponent(name),true);
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
document.getElementById("responseGet").innerHTML=xhr.responseText;
}
};
xhr.send();
}
<?php
// PHP reads value using $_GET
echo "GET Received: ".$_GET["name"];
?>
// HTML + JavaScript + PHP POST example
<input type="text" id="namePost">
<button onclick="sendPost()">Send POST</button>
<div id="responsePost"></div>
function sendPost(){
var name=document.getElementById("namePost").value;
var xhr=new XMLHttpRequest();
xhr.open("POST","post_process.php",true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
document.getElementById("responsePost").innerHTML=xhr.responseText;
}
};
xhr.send("name="+encodeURIComponent(name));
}
<?php
// PHP reads value using $_POST
echo "POST Received: ".$_POST["name"];
?>
The server response is displayed instantly below the input fields without refreshing the page, demonstrating true AJAX behavior.
Modify the input values and observe how GET changes the URL while POST keeps data hidden.