← Back to Chapters

PHP AJAX – $_GET & $_POST Methods

? PHP AJAX – $_GET & $_POST Methods

? Quick Overview

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.

? Key Concepts

  • AJAX enables asynchronous server communication
  • $_GET reads data from URL parameters
  • $_POST reads data from request body
  • PHP processes data and returns dynamic output

? Syntax & Theory

JavaScript sends data using XMLHttpRequest. PHP scripts read the incoming values using $_GET or $_POST and respond with output that updates the page dynamically.

? Code Examples

GET Method

? View Code Example
// 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"];
?>

POST Method

? View Code Example
// 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"];
?>

? Live Output / Explanation

The server response is displayed instantly below the input fields without refreshing the page, demonstrating true AJAX behavior.

? Interactive Idea

Modify the input values and observe how GET changes the URL while POST keeps data hidden.

? Use Cases

  • Search filters
  • Form submissions
  • Live validation
  • CRUD operations

✅ Tips & Best Practices

  • Use GET for non-sensitive data
  • Use POST for secure operations
  • Always sanitize inputs

? Try It Yourself

  • Create a multi-field AJAX form
  • Log server responses dynamically
  • Compare GET vs POST behavior