How can PHP and JavaScript work together to dynamically update content without page reloads?

To dynamically update content without page reloads, PHP can be used to fetch data from a database or external source, and then JavaScript can be used to manipulate the DOM and update the content on the page. This can be achieved by making an AJAX request to a PHP script that returns the updated content in JSON format, which can then be processed by JavaScript to update the page.

<?php
// Assume this PHP script fetches data from a database
$data = fetchDataFromDatabase();

// Convert data to JSON format
$jsonData = json_encode($data);

// Output JSON data
header('Content-Type: application/json');
echo $jsonData;
?>