What are some best practices for integrating JavaScript with PHP to display and edit MySQL data in a form?

When integrating JavaScript with PHP to display and edit MySQL data in a form, it is important to use AJAX to send requests to the server without reloading the page. This allows for a smoother user experience and real-time updates. Additionally, using JSON to format data between PHP and JavaScript can simplify data manipulation and reduce errors.

<?php
// PHP code to fetch data from MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch data from MySQL
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

// Convert data to JSON format
$data = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

// Output JSON data
echo json_encode($data);

// Close connection
$conn->close();
?>