How can PHP and JavaScript be integrated to trigger a modal window based on a detected error in a PHP script?

To trigger a modal window based on a detected error in a PHP script, you can use JavaScript to display the modal when an error occurs in the PHP code. You can pass the error message from PHP to JavaScript using AJAX or by embedding it directly in the HTML response. Then, use JavaScript to show the modal with the error message.

<?php
// PHP script that may generate an error
$error = false;

// Check for error condition
if($error) {
    // Send error message to JavaScript
    echo '<script>var errorMessage = "An error has occurred";</script>';
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Error Modal Example</title>
    <script>
        // Check for error message and display modal
        if(typeof errorMessage !== 'undefined') {
            window.onload = function() {
                document.getElementById('modal').style.display = 'block';
                document.getElementById('error-message').innerHTML = errorMessage;
            }
        }
    </script>
</head>
<body>
    <div id="modal" style="display:none;">
        <div id="error-message"></div>
    </div>
</body>
</html>