How can using JavaScript for page navigation impact PHP session data retention?

When using JavaScript for page navigation, the browser may not always send the appropriate headers to the server, causing PHP session data to not be retained between page loads. To ensure PHP session data retention, you can include a JavaScript function that makes an AJAX request to a PHP script that updates the session data before navigating to a new page.

// PHP script to update session data
session_start();

// Update session data
$_SESSION['example_data'] = 'updated';

// JavaScript function to update session data before navigating
<script>
function updateSessionData() {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'update_session.php', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send();
}
</script>