Tutorials Logic, IN info@tutorialslogic.com

AJAX PHP Backend Integration

PHP Endpoint Contract

A PHP AJAX endpoint should validate method and content type, parse input once, enforce authentication and authorization, call a focused service, and return one JSON response with an intentional status. Browser-side validation improves feedback but never replaces server validation.

PHP as an AJAX Backend

A PHP endpoint can receive an asynchronous browser request, validate its input, perform application work, and return JSON. Set Content-Type to application/json, encode one predictable response shape, and use an appropriate HTTP status for failures.

A reliable AJAX endpoint should also validate request data, return a suitable HTTP status code for failures, and keep the JSON response shape predictable. This makes frontend error handling easier and prevents invalid input from reaching database logic.

PHP: Handling GET and POST AJAX Requests

PHP: Handling GET and POST AJAX Requests
<?php
// 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

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

PHP Backend: search.php
<?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

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);
});

Secure PHP Response

Use JSON_THROW_ON_ERROR when decoding and encoding, PDO prepared statements for database values, and deployment-provided credentials. Start no HTML output before setting headers. Translate known validation and conflict failures into stable response fields rather than exposing warnings, stack traces, or SQL messages.

Session-based browser writes still need CSRF protection. CORS does not prevent forged same-browser submissions. Set a request-size limit, reject unexpected fields when appropriate, and log a correlation ID so a safe client message can be tied to server diagnostics.

Before you move on

AJAX PHP Backend Integration Mastery Check

4 checks
  • 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.
  • A reliable AJAX endpoint should also validate request data, return a suitable HTTP status code for failures, and keep the JSON response shape predictable.
  • This makes frontend error handling easier and prevents invalid input from reaching database logic.
Next Step
Next Practice

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Browse Free Tutorials

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