AJAX - AJAX PHP
Goal
We’ll create a form where the user enters their name, and AJAX will send it to a PHP file. The PHP file will return a greeting message, which will be displayed on the same page.
1. HTML + JavaScript (AJAX)
<!DOCTYPE html>
<html>
<head>
<title>AJAX with PHP Example</title>
</head>
<body>
<h2>Enter Your Name:</h2>
<input type="text" id="nameInput" placeholder="Type your name">
<button onclick="sendName()">Submit</button>
<p id="responseText"></p>
<script>
function sendName() {
var name = document.getElementById("nameInput").value;
var xhr = new XMLHttpRequest(); // Create AJAX object
xhr.open("POST", "process.php", true); // Send data to process.php
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("responseText").innerHTML = xhr.responseText;
}
};
xhr.send("name=" + encodeURIComponent(name)); // Send name data to PHP
}
</script>
</body>
</html>
2. PHP File (process.php)
<?php
if (isset($_POST['name'])) {
$name = htmlspecialchars($_POST['name']); // Clean input
echo "Hello, " . $name . "! Welcome to AJAX with PHP.";
} else {
echo "No name received.";
}
?>
How It Works
-
The user types a name and clicks the button.
-
JavaScript sends the name to process.php via AJAX (without page reload).
-
The PHP file processes the request and returns a greeting.
-
The response is displayed instantly on the same page.