HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP AJAX Introduction

AJAX stands for **Asynchronous JavaScript and XML**. It is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


How AJAX Works

The flow of an AJAX request looks like this:

  1. An event occurs on a web page (e.g., a button click).
  2. An **XMLHTTPRequest** object (or the modern **fetch API**) is created by JavaScript.
  3. The object sends a request to a PHP file on the web server.
  4. PHP processes the request (e.g., looks up a database) and sends back the result.
  5. JavaScript reads the response and updates the page content without a refresh.

Why Use AJAX with PHP?

  • Better User Experience: Users don't have to wait for the whole page to reload.
  • Partial Updates: Change only a small part of the page (e.g., live search results or a notification badge).
  • Speed: Less data is transferred between the browser and the server.
  • Interactivity: Create features like "infinite scroll" or real-time form validation.

A Simple PHP AJAX Example

Let's say we have a PHP file that returns a greeting. We can call it using JavaScript's fetch() API.

The PHP File (get_hint.php)

<?php
    $name = $_GET['name'];
    echo "Hello, " . htmlspecialchars($name) . "! The time is " . date("H:i:s");
?>

The JavaScript Code

async function showGreeting() {
    let response = await fetch('get_hint.php?name=John');
    let data = await response.text();
    document.getElementById("display").innerHTML = data;
}
What happened? When showGreeting() is called, the browser asks get_hint.php for information. PHP runs, generates the string, and sends it back. JavaScript then puts that string inside an HTML element.

XML vs. JSON

Although the "X" in AJAX stands for XML, modern web development almost always uses **JSON** instead. JSON is smaller, faster to parse, and works natively with JavaScript arrays and objects. In the next lessons, we'll focus on sending JSON data from PHP to AJAX.

Important: AJAX is not a programming language. It is a technique that uses a combination of JavaScript (to send the request) and PHP (to handle the server-side logic).

Summary

  • AJAX allows updating parts of a page without a full reload.
  • It uses JavaScript to communicate with PHP scripts.
  • It improves speed and user experience.
  • fetch() is the modern way to make AJAX requests.
Tip: You can see AJAX in action every time you see "live suggestions" while typing into a search engine!

What's Next?

While AJAX often uses JSON, some legacy systems still use XML. Let's briefly look at how PHP handles **XML** data in the next lesson.