Home >Backend Development >PHP Tutorial >How to Fix jQuery Ajax Calls Failing to Retrieve Data from MySQL?
Using jQuery Ajax to Retrieve Data from MySQL
This article addresses an issue where an Ajax code attempts to retrieve records from a MySQL table but fails. The provided PHP code attempts to connect to MySQL and fetch data from the "users" table, but the methods used are outdated.
Solution
To resolve this, the code should be updated to use more modern and secure methods for connecting to MySQL and retrieving data. Here's a revised version:
$con = mysqli_connect("localhost", "root", "", "simple_ajax"); $result = mysqli_query($con, "SELECT * FROM users");
In this version:
Displaying the Data
To display the retrieved data in the HTML page, we can use the following PHP code:
echo "<table border='1'>"; echo "<tr><th>Name</th><th>Address</th></tr>"; while ($row = mysqli_fetch_array($result)) { echo "<tr><td>$row[1]</td><td>$row[2]</td></tr>"; } echo "</table>";
This code generates a simple HTML table with columns for Name and Address, populated with the data from the MySQL table.
Complete Ajax Code
Here's the updated jQuery Ajax code to display the data:
$(document).ready(function() { $("#display").click(function() { $.ajax({ type: "GET", url: "display.php", dataType: "html", success: function(response) { $("#responsecontainer").html(response); } }); }); });
Display Page
The display.php page that retrieves and displays the data should use the code mentioned above.
This updated code should allow you to successfully retrieve and display data from the MySQL table using jQuery Ajax.
The above is the detailed content of How to Fix jQuery Ajax Calls Failing to Retrieve Data from MySQL?. For more information, please follow other related articles on the PHP Chinese website!