Why Your jQuery AJAX and MySQL Code Fails (and How to Fix It)
The code snippet you are working with presents a classic set of issues that prevent it from functioning in any modern web environment. The primary failure point is not the logic within the script tags, but the underlying technology stack used to interact with the database. You are using the mysql_* family of PHP functions, which have been deprecated since PHP 5.5.0 and removed entirely in PHP 7.0.0. Furthermore, the JavaScript implementation relies on synchronous AJAX (async: false) and global variables that introduce unnecessary latency and coupling.
The Database Connectivity Crisis
The first line of defense in any web application is secure and supported database connectivity. Your current script uses $con = mysql_connect(...). This function sends a simple socket connection request without verifying credentials or handling errors gracefully. In a production environment, this approach is unacceptable because it offers no protection against SQL injection if you were to build dynamic queries later, and it provides zero insight into connection failures.
You must migrate to mysqli or PDO immediately. Using prepared statements is not just a best practice; it is a requirement for security. Here is how the PHP backend should look when using mysqli:
<?php
// Replace deprecated mysql_* with mysqli
$host = "localhost";
$user = "root";
$pass = ""; // Change this in production!
$dbname = "simple_ajax";
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Use prepared statements to fetch data safely
$stmt = $conn->prepare("SELECT Name, Address FROM users");
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . htmlspecialchars($row['Name']) . "</td>";
echo "<td>" . htmlspecialchars($row['Address']) . "</td>";
echo "</tr>";
}
} else {
echo "No records found.";
}
$conn->close();
?>
Notice the use of htmlspecialchars(). When rendering user-generated data like names and addresses directly into an HTML table, you are vulnerable to Cross-Site Scripting (XSS) attacks. This simple function escapes characters that could break the HTML or inject malicious scripts.
The Synchronous AJAX Trap
Your client-side code sets async: false. While this might seem necessary if you want to pause execution until the data loads, it is a performance anti-pattern in modern browsers. Setting an AJAX request to synchronous blocks the entire main thread of the browser. If the server takes even a moment to respond, the user interface freezes, and the page becomes unresponsive.
Additionally, declaring var response = '' at the top level and assigning it inside the success callback is inefficient. You should bind the data directly to the DOM element you intend to update immediately upon success. This eliminates the need for a global variable and ensures the data is rendered exactly where the user expects it.
Here is an improved, asynchronous implementation:
<script src="jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
var $target = $('#div1'); // Select the container to update
$.ajax({
type: "GET",
url: "Records.php", // Ensure this URL is correct relative to your server
dataType: 'html', // Tell jQuery we expect HTML back
success: function(text) {
$target.html(text); // Directly inject the response into the div
},
error: function(xhr, status, error) {
console.error("AJAX Error:", status, error);
$target.html("Failed to load records.");
}
});
});
</script>
Structuring Your HTML Correctly
Your original HTML places the button inside the <body> but expects the AJAX response to populate div1. However, the script runs on document.ready, which fires before the user clicks the button. The code executes immediately upon page load, fetching data automatically rather than waiting for user interaction.
If your intent is to fetch records only when the user clicks "Get Records", you must move the AJAX call inside an event listener attached to that specific button element. This decouples the data loading from the initial page render and provides a better user experience by only incurring network costs when needed.
Moving Forward with Modern Standards
While jQuery is still widely used, understanding why your current setup fails highlights the necessity of moving toward modern standards. If you are building new applications or maintaining legacy ones where security is paramount, consider adopting native fetch API alongside ES6+ features or leveraging a framework like Laravel, which handles routing, authentication, and AJAX interactions seamlessly.
For more guidance on integrating these technologies into a robust architecture, resources like https://laravelcompany.com offer deeper dives into backend patterns that abstract away the raw PHP/MySQL connections you are currently managing manually.