How can a JSON API be implemented to handle AJAX requests in a PHP CMS?

To implement a JSON API to handle AJAX requests in a PHP CMS, you can create a PHP script that receives AJAX requests, processes them, and returns JSON responses. This script can interact with the CMS database to fetch or update data based on the request parameters. By using JSON as the data format, you can easily communicate between the front-end and back-end of your application.

<?php

// Check if this is an AJAX request
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    
    // Include necessary files for CMS functionality
    require_once 'config.php';
    require_once 'database.php';

    // Process the AJAX request
    if(isset($_POST['action'])) {
        $action = $_POST['action'];

        // Handle different actions
        switch($action) {
            case 'get_data':
                // Query the database to fetch data
                $data = fetchDataFromCMS($_POST['param']);
                echo json_encode($data);
                break;
            case 'update_data':
                // Update data in the CMS database
                $result = updateDataInCMS($_POST['param']);
                echo json_encode($result);
                break;
            default:
                echo json_encode(['error' => 'Invalid action']);
        }
    } else {
        echo json_encode(['error' => 'No action specified']);
    }
} else {
    // Handle non-AJAX requests
    echo json_encode(['error' => 'Invalid request']);
}

?>