What are best practices for handling PHP and JavaScript interactions to display error messages based on SQL query results?

When handling PHP and JavaScript interactions to display error messages based on SQL query results, it is best practice to use AJAX to send the query request to the server, process the query in PHP, and return the result to JavaScript for display. This allows for seamless communication between the frontend and backend, enabling real-time error handling without refreshing the page.

// PHP code to handle SQL query and return result to JavaScript
<?php

// Perform SQL query
// Check if query was successful
if ($query_success) {
    $result = "Query successful!";
} else {
    $result = "Query failed!";
}

// Return result to JavaScript
echo json_encode(['result' => $result]);

?>