← Back to Chapters

PHP AJAX Introduction

⚡ PHP AJAX Introduction

? Quick Overview

AJAX (Asynchronous JavaScript and XML) is a technique used to create dynamic, interactive web applications. It allows web pages to update specific parts without reloading the entire page. PHP commonly works with AJAX to handle server-side logic asynchronously.

? Key Concepts

  • Asynchronous communication between browser and server
  • JavaScript sends HTTP requests in the background
  • PHP processes requests and sends responses
  • Page updates without full reload

? Syntax & Theory

AJAX works by sending HTTP requests using JavaScript. PHP receives the request, processes data, and returns a response (HTML or JSON). JavaScript then updates the page dynamically.

? Code Example

? View Code Example
// HTML elements and JavaScript AJAX request
<button onclick="loadData()">Get Data</button>
<div id="response"></div>

// AJAX function using XMLHttpRequest
function loadData() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "data.php", true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("response").innerHTML = xhr.responseText;
        }
    };
    xhr.send();
}

? PHP Server Script

? View Code Example
// PHP script responding to AJAX request
<?php
echo "Hello, this is data returned from PHP!";
?>

? Live Output / Explanation

When the button is clicked, JavaScript sends an asynchronous request to the PHP file. The PHP script responds with text, which is inserted into the page without refreshing.

? Interactive Concept

You can replace XMLHttpRequest with the modern fetch() API to perform cleaner and promise-based AJAX requests.

? Solution using Fetch API
// Modern fetch() implementation
function loadData() {
    fetch('data.php')
        .then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.text();
        })
        .then(data => {
            document.getElementById("response").innerHTML = data;
        })
        .catch(error => {
            console.error('There was a problem with the fetch operation:', error);
        });
}

?️ Use Cases

  • Live search suggestions
  • Form submissions without page reload
  • Dynamic content loading
  • Real-time data updates

✅ Tips & Best Practices

  • Always validate and sanitize server-side input
  • Prefer JSON for structured data exchange
  • Handle errors gracefully in JavaScript

? Try It Yourself

  • Send form data using POST via AJAX
  • Use fetch() instead of XMLHttpRequest
  • Return JSON from PHP and parse it in JavaScript