Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

AJAX with PHP

PHP as an AJAX Backend

PHP is one of the most common server-side languages used with AJAX. A PHP script receives the AJAX request, processes it (queries a database, performs logic), and returns a JSON response. The key is to output the correct Content-Type header and use json_encode() to serialize the response.

PHP: Handling GET and POST AJAX Requests
// api.php — PHP AJAX endpoint

// Always set JSON content type first
header('Content-Type: application/json');

// Allow cross-origin requests if needed
header('Access-Control-Allow-Origin: *');

// Detect if this is an AJAX request
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
          strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Read query parameters
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $page   = isset($_GET['page'])   ? (int)$_GET['page']   : 1;

    // Simulate database results
    $results = [
        ['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com'],
        ['id' => 2, 'name' => 'Bob',   'email' => 'bob@example.com'],
    ];

    echo json_encode(['success' => true, 'data' => $results, 'page' => $page]);

} elseif ($method === 'POST') {
    // Read JSON body (sent with Content-Type: application/json)
    $input = json_decode(file_get_contents('php://input'), true);

    // Or read form-encoded body (sent with FormData or URL-encoded)
    // $name = $_POST['name'] ?? '';

    $name  = $input['name']  ?? '';
    $email = $input['email'] ?? '';

    if (empty($name) || empty($email)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Name and email are required']);
        exit;
    }

    // Process and respond
    echo json_encode(['success' => true, 'message' => "User $name created", 'id' => 42]);
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
JavaScript: Calling the PHP Endpoint
// GET request to PHP endpoint
fetch('/api.php?search=alice&page=1')
  .then(res => res.json())
  .then(data => {
    if (data.success) {
      data.data.forEach(user => console.log(user.name));
    }
  });

// POST request to PHP endpoint
fetch('/api.php', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Charlie', email: 'charlie@example.com' })
})
  .then(res => res.json())
  .then(data => {
    if (data.success) {
      console.log(data.message); // "User Charlie created"
    } else {
      console.error(data.error);
    }
  });

Complete Example: Search Autocomplete

Here is a full working example of a live search/autocomplete feature using AJAX and PHP.

PHP Backend: search.php
// search.php
header('Content-Type: application/json');

$query = strtolower(trim($_GET['q'] ?? ''));

if (strlen($query) < 2) {
    echo json_encode([]);
    exit;
}

// In a real app, query your database here
// $stmt = $pdo->prepare("SELECT name FROM products WHERE name LIKE ? LIMIT 10");
// $stmt->execute(["%$query%"]);
// $results = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Simulated data
$products = ['Apple', 'Apricot', 'Banana', 'Blueberry', 'Cherry', 'Coconut', 'Grape', 'Mango'];
$results = array_values(array_filter($products, fn($p) => str_contains(strtolower($p), $query)));

echo json_encode($results);
JavaScript Frontend: Autocomplete
const searchInput = document.getElementById('search-input');
const suggestionsList = document.getElementById('suggestions');
let debounceTimer;

searchInput.addEventListener('input', function () {
  const query = this.value.trim();
  clearTimeout(debounceTimer);

  if (query.length < 2) {
    suggestionsList.innerHTML = '';
    return;
  }

  debounceTimer = setTimeout(async () => {
    try {
      const res = await fetch(`/search.php?q=${encodeURIComponent(query)}`);
      const results = await res.json();

      suggestionsList.innerHTML = results.length
        ? results.map(item => `<li class="suggestion-item">${item}</li>`).join('')
        : '<li class="no-results">No results found</li>';

      // Handle suggestion click
      suggestionsList.querySelectorAll('.suggestion-item').forEach(li => {
        li.addEventListener('click', () => {
          searchInput.value = li.textContent;
          suggestionsList.innerHTML = '';
        });
      });
    } catch (err) {
      console.error('Search failed:', err);
    }
  }, 300);
});

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.