AJAX PHP


AJAX alone cannot perform server-side operations; it needs a backend script to process requests and return responses. PHP is one of the most popular server-side languages used with AJAX because it is lightweight, widely supported, and easy to integrate with HTML and JavaScript.

This tutorial explains how to use AJAX with PHP to create dynamic, responsive web applications. You’ll learn how to send data to PHP scripts, retrieve server responses, and update web pages without reloading.

How AJAX Interacts with PHP

The typical flow:

  1. User triggers an action on the web page (click, input, selection).

  2. JavaScript creates an XMLHttpRequest object and sends a request to a PHP file.

  3. PHP processes the request, optionally interacting with a database or performing calculations.

  4. PHP returns a response (text, HTML, XML, or JSON).

  5. JavaScript receives the response and updates the HTML dynamically.

Basic Example: Sending a Request to PHP

HTML File: index.html

<!DOCTYPE html>
<html>
<head>
  <title>AJAX PHP Example</title>
  <script>
    function fetchMessage() {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "server.php", true);
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
          document.getElementById("result").innerHTML = xhr.responseText;
        }
      };
      xhr.send();
    }
  </script>
</head>
<body>
  <h2>AJAX with PHP</h2>
  <button onclick="fetchMessage()">Fetch Message</button>
  <div id="result" style="margin-top:20px;"></div>
</body>
</html>

PHP File: server.php

<?php
echo "Hello! This message is returned from PHP using AJAX.";
?>

Clicking the button fetches the message from PHP without reloading the page.

Sending Data to PHP

AJAX can send data to PHP using GET or POST methods.

Example: Sending data with GET

var xhr = new XMLHttpRequest();
xhr.open("GET", "server.php?name=Sunita&age=25", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById("result").innerHTML = xhr.responseText;
  }
};
xhr.send();

PHP (server.php)

<?php
$name = $_GET['name'];
$age = $_GET['age'];
echo "Hello $name! You are $age years old.";
?>

Example: Sending data with POST

var xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById("result").innerHTML = xhr.responseText;
  }
};
xhr.send("name=Sunita&age=25");

PHP (server.php)

<?php
$name = $_POST['name'];
$age = $_POST['age'];
echo "Hello $name! You are $age years old.";
?>

Returning JSON Data from PHP

JSON is widely used for structured data exchange between PHP and JavaScript.

PHP File: server.php

<?php
$data = array("name" => "Sunita", "age" => 25, "course" => "Web Development");
echo json_encode($data);
?>

JavaScript

var xhr = new XMLHttpRequest();
xhr.open("GET", "server.php", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var obj = JSON.parse(xhr.responseText);
    document.getElementById("result").innerHTML = 
      "Name: " + obj.name + ", Age: " + obj.age + ", Course: " + obj.course;
  }
};
xhr.send();

Dynamic Form Processing

You can use AJAX to validate forms without reloading the page.

HTML Example:

<input type="text" id="username" placeholder="Enter username">
<button onclick="checkUsername()">Check</button>
<div id="status"></div>

<script>
function checkUsername() {
  var user = document.getElementById("username").value;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "check.php?username=" + user, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      document.getElementById("status").innerHTML = xhr.responseText;
    }
  };
  xhr.send();
}
</script>

PHP (check.php)

<?php
$existingUsers = array("Riya", "Ananya", "Meera");
$username = $_GET['username'];

if(in_array($username, $existingUsers)) {
    echo "Username already taken";
} else {
    echo "Username available";
}
?>

This approach allows real-time validation without refreshing the page.

Advantages of Using AJAX with PHP

  1. Real-time updates – Fetch data or process forms instantly.

  2. Better user experience – No page reloads required.

  3. Reduced server load – Only part of the page updates.

  4. Flexible data handling – Can work with text, HTML, JSON, or XML.

  5. Dynamic applications – Build interactive features like live search, auto-suggestions, and notifications.

Common Use Cases

  • Form validation

  • Live search suggestions

  • Fetching database content dynamically

  • Polls and surveys

  • Chat applications

  • Dynamic dashboards

Summary of the Tutorial

Using AJAX with PHP allows web developers to create fast, responsive, and interactive web pages. PHP handles server-side processing, while AJAX ensures smooth communication without full page reloads.

Key points:

  • Use XMLHttpRequest to send data to PHP asynchronously.

  • GET and POST methods determine how data is sent.

  • PHP can return plain text, HTML, XML, or JSON.

  • AJAX with PHP is ideal for dynamic content, form validation, and real-time updates.

Mastering AJAX with PHP is a fundamental skill for modern web development.


Practice Questions

  1. Create an HTML page with a button that fetches a message from a PHP file using AJAX and displays it in a div.

  2. Modify the previous example to send a user’s name via GET to a PHP file and display a personalized greeting.

  3. Create a form with two fields (name and age). Use AJAX POST to send data to PHP and display the response.

  4. Write a PHP script that returns JSON data for a user (name, age, course). Use AJAX to fetch and display this data dynamically.

  5. Implement a username availability checker using AJAX and PHP. Display “Available” or “Taken” in real time.

  6. Create a dropdown menu with three options. Send the selected option to PHP using AJAX and display a corresponding message.

  7. Create a page that fetches the current server time from PHP every 5 seconds without reloading the page.

  8. Implement error handling in an AJAX request to a PHP file. Display an alert if the request fails.

  9. Create a small page with two buttons, each fetching data from a different PHP file and displaying it in separate div elements.

  10. Build a live feedback form that sends user comments via AJAX POST to a PHP script and displays a confirmation message without reloading.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top