AJAX Intro

Ma Mahalakshmi V Updated 14 Nov 2026
5 min read ·Lesson 220 of 255

What Is AJAX?

In simple terms: Normally, when you click a link or submit a form, the browser loads a completely new page. AJAX lets a web page talk to the server in the background and update only part of the page — showing search suggestions as you type, checking if a username is available, adding an item to the cart, or loading more comments — without a full page reload.

Technically: AJAX originally stood for Asynchronous JavaScript and XML. JavaScript in the browser sends an HTTP request to the server, continues running while waiting (asynchronously), and updates the page (the DOM) when the response arrives. Today, requests are usually sent with the Fetch API (fetch()), and responses are mostly JSON rather than XML — but the name AJAX remains. On the server side, a PHP script simply receives a normal HTTP request and returns data.

Full Page Load vs AJAX

Traditional request:                         AJAX request:
Browser ──request──► PHP                     JavaScript ──fetch()──► PHP endpoint
Browser ◄──complete HTML page── PHP           JavaScript ◄──JSON data── PHP
(whole page reloads)                          (JavaScript updates one part of the page)
Full Page LoadAJAX
Data transferredThe whole pageOnly the data needed
User experiencePage flickers, scroll position resetsSmooth, partial updates
Server outputHTML pageUsually JSON (sometimes HTML fragments or XML)
Works without JavaScriptYesNo — provide a fallback for essential features

How an AJAX Request Works

1. An event happens          the user clicks a button or types in a field
2. JavaScript sends request  fetch('/api/server-time.php')
3. PHP processes it          reads parameters, queries the database, returns JSON
4. JavaScript receives data  await response.json()
5. The page is updated       element.textContent = data.time

A First Example

The PHP Endpoint: api/server-time.php

<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

$now = new DateTimeImmutable('now', new DateTimeZone('Asia/Kolkata'));

echo json_encode([
    'time' => $now->format('H:i:s'),
    'date' => $now->format('l, d F Y'),
    'timezone' => $now->getTimezone()->getName(),
], JSON_THROW_ON_ERROR);

Response (example)

{"time":"14:05:09","date":"Thursday, 15 October 2026","timezone":"Asia/Kolkata"}

You can open api/server-time.php directly in the browser to see this JSON — an AJAX endpoint is an ordinary PHP script that outputs data instead of a page.

The Page: index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Server Time</title>
</head>
<body>
    <button id="refresh" type="button">Get server time</button>
    <p id="result" aria-live="polite">Click the button.</p>

    <script>
        const button = document.getElementById('refresh');
        const result = document.getElementById('result');

        button.addEventListener('click', async () => {
            result.textContent = 'Loading…';

            try {
                const response = await fetch('api/server-time.php');

                if (!response.ok) {
                    throw new Error(`Server responded with ${response.status}`);
                }

                const data = await response.json();
                result.textContent = `${data.date}, ${data.time} (${data.timezone})`;
            } catch (error) {
                result.textContent = 'Could not load the time. Please try again.';
                console.error(error);
            }
        });
    </script>
</body>
</html>

How It Works

  1. Clicking the button runs an async function.
  2. fetch() sends a GET request to the PHP endpoint. await pauses this function (not the whole page) until the response arrives.
  3. response.ok is true for HTTP status codes 200–299. fetch() does not throw for 404 or 500 responses, so the status must be checked explicitly.
  4. response.json() parses the JSON body into a JavaScript object.
  5. Only the paragraph's text changes; the rest of the page stays as it is.
  6. textContent (instead of innerHTML) inserts the data as plain text, which prevents XSS if a value ever contains HTML.
  7. aria-live="polite" makes screen readers announce the updated text.

The Older Way: XMLHttpRequest

Before fetch() (supported in all modern browsers), AJAX used the XMLHttpRequest object:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'api/server-time.php');
xhr.onload = () => {
    if (xhr.status === 200) {
        const data = JSON.parse(xhr.responseText);
        document.getElementById('result').textContent = data.time;
    }
};
xhr.send();

You will see it in older code and in libraries such as jQuery's $.ajax(). For new code, fetch() with async/await is simpler and more readable.


What the Server Side Must Do

An AJAX endpoint follows the same rules as any PHP page — plus a few specific to data APIs:

ResponsibilityHow
Declare the response typeContent-Type: application/json; charset=utf-8
Return meaningful status codes200 success, 400/422 invalid input, 401/403 not allowed, 404 not found, 500 errors
Validate all inputParameters from AJAX requests are user input, just like form fields
Check authentication and permissionsUse the session as for normal pages; never trust a user ID sent by JavaScript
Protect state-changing requestsUse POST (or PUT/PATCH/DELETE) with a CSRF token (see CSRF Protection)
Output only dataNo HTML layout, no stray whitespace or warnings before the JSON

Same-Origin Policy and CORS

By default, browsers only allow JavaScript to read responses from the same origin (same scheme, host, and port) as the page. If a page on https://app.example.com calls an API on https://api.example.com, the API must send CORS headers (such as Access-Control-Allow-Origin: https://app.example.com). Never answer with Access-Control-Allow-Origin: * for endpoints that use cookies or return private data.


AJAX Lessons in This Section

LessonTopic
AJAX PHPWriting PHP endpoints and sending GET and POST requests
AJAX DatabaseLoading database records without reloading the page
AJAX XMLExchanging XML instead of JSON
AJAX Live SearchSearch suggestions while typing
AJAX PollA voting widget that updates results instantly
AJAX with JSONStructured JSON APIs and error handling

Common Mistakes

Ignoring HTTP Error Statuses

Effect: fetch() resolves for 404 and 500 responses; the code then fails to parse an error page as JSON.

Fix: Check response.ok before reading the data.

Inserting Responses With innerHTML

Effect: XSS vulnerabilities if data contains HTML.

Fix: Use textContent, or build elements with DOM methods.

Stray Output Before JSON

Effect: Warnings, whitespace, or a BOM before the JSON make response.json() fail.

Fix: Log errors instead of displaying them; omit closing ?> tags in PHP files.

Making Essential Features Depend Only on JavaScript

Effect: Features break when JavaScript fails or is blocked.

Fix: Use progressive enhancement: a normal form or link works without JavaScript, and AJAX improves it.


Best Practices

  • Use fetch() with async/await and handle network errors and HTTP status codes.
  • Return JSON with a correct Content-Type and meaningful status codes.
  • Treat every AJAX parameter as untrusted input and check permissions on the server.
  • Update the page with textContent or DOM methods to avoid XSS.
  • Inspect requests and responses in the browser's developer tools (Network tab) while developing.

Official reference: https://www.php.net/manual/en/tutorial.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about AJAX Intro and get answers drawn from it.

Signed-in readers only.