Introduction to AJAX


What is AJAX?

  • AJAX = Asynchronous JavaScript and XML

  • Technique to send and receive data from a server without reloading the webpage.

  • Creates faster, more dynamic, user-friendly websites.

  • Nowadays, JSON is used more than XML for data exchange.


How Does AJAX Work?

  1. JavaScript sends an HTTP request to the server (usually via XMLHttpRequest or fetch).

  2. Server processes the request (e.g., PHP script).

  3. Server returns data (JSON, HTML, text).

  4. JavaScript receives the response and updates the webpage dynamically.


Basic AJAX Example Using XMLHttpRequest

html
<button onclick="loadData()">Load Data</button>
<div id="result"></div>

<script>
function loadData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);

xhr.onload = function() {
if (this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};

xhr.send();
}
</script>


PHP Script (data.php)

php
<?php
echo "Hello from the server! The time is " . date("h:i:s A");
?>

Modern AJAX with fetch()

html
<button onclick="loadData()">Load Data</button>
<div id="result"></div>

<script>
function loadData() {
fetch('data.php')
.then(response => response.text())
.then(data => {
document.getElementById('result').innerHTML = data;
})
.catch(error => console.error('Error:', error));
}
</script>


Sending Data via POST with AJAX & PHP

JavaScript (fetch POST example)

js
function sendData() {
fetch('process.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'name=Alice&age=25'
})
.then(response => response.text())
.then(data => console.log(data));
}

PHP (process.php)

php
<?php
$name = $_POST['name'] ?? 'Unknown';
$age = $_POST['age'] ?? 'Unknown';

echo "Received name: $name and age: $age";
?>


Summary

Step Description
Create AJAX Request Use XMLHttpRequest or fetch() in JS
Server-side Script PHP (or other) handles request and returns data
Update Page JS updates the DOM dynamically without reload

Leave a Reply

Your email address will not be published. Required fields are marked *