R
Rishtaara
PHP Fundamentals
Lesson 30 of 32Article19 min

AJAX — Introduction & PHP Backend

AJAX (Asynchronous JavaScript and XML) loads data in the background without reloading the page. Today we mostly use JSON instead of XML.

AJAX Introduction

AJAX (Asynchronous JavaScript and XML) loads data in the background without reloading the page. Today we mostly use JSON instead of XML.

Real-life example: AJAX is texting the kitchen for today's specials while you keep chatting at the table — no need to stand up and walk over.

  • Browser sends HTTP request via fetch() or XMLHttpRequest
  • PHP script returns JSON or HTML fragment
  • JavaScript updates part of the page
  • User sees fast, app-like experience

PHP as AJAX endpoint

A PHP API file sets Content-Type: application/json, reads input, queries data, and echo json_encode($result).

Real-life example: PHP endpoint is a vending machine slot — JavaScript inserts coins (request), PHP drops the snack (JSON).

api/courses.php
<?php
header("Content-Type: application/json");

$courses = [
  ["id" => 1, "title" => "PHP Fundamentals"],
  ["id" => 2, "title" => "MySQL Basics"],
];

echo json_encode($courses);
fetch from JavaScript
fetch("/api/courses.php")
  .then((res) => res.json())
  .then((data) => {
    console.log(data);
    document.getElementById("list").innerHTML =
      data.map((c) => `<li>${c.title}</li>`).join("");
  });