What are the best practices for handling JavaScript calls from PHP scripts in a web development environment?

When handling JavaScript calls from PHP scripts in a web development environment, it is important to properly sanitize and validate any user input to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. Additionally, using JSON to pass data between PHP and JavaScript can help ensure data integrity and compatibility between the two languages.

<?php
// Sanitize and validate user input
$input = $_POST['input'];
$sanitized_input = filter_var($input, FILTER_SANITIZE_STRING);

// Encode data as JSON for passing between PHP and JavaScript
$data = array('key' => $sanitized_input);
$json_data = json_encode($data);

// Output JSON data for JavaScript to consume
echo $json_data;
?>