What best practices should be followed when handling AJAX requests in PHP scripts for dynamic dropdown selection?

When handling AJAX requests in PHP scripts for dynamic dropdown selection, it is important to sanitize and validate user input to prevent SQL injection attacks. Additionally, the PHP script should fetch data from the database based on the user input, format it appropriately, and return it in a JSON format to be processed by the frontend.

<?php

// Sanitize and validate user input
$selectedOption = isset($_POST['selectedOption']) ? $_POST['selectedOption'] : '';

// Fetch data from the database based on user input
// Replace this with your own database connection and query
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM options WHERE parent_id = :selectedOption');
$stmt->bindParam(':selectedOption', $selectedOption);
$stmt->execute();
$options = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Format data and return it in JSON format
header('Content-Type: application/json');
echo json_encode($options);

?>