Home > Backend Development > PHP Tutorial > How to Fix jQuery Ajax Calls Failing to Retrieve Data from MySQL?

How to Fix jQuery Ajax Calls Failing to Retrieve Data from MySQL?

Barbara Streisand
Release: 2024-12-07 21:11:15
Original
218 people have browsed it

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");
Copy after login

In this version:

  • We use mysqli_connect function instead of mysql_connect for database connection.
  • The database name is provided as an additional parameter to mysqli_connect.
  • We use mysqli_query instead of mysql_query to execute the query.

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>";
Copy after login

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);
      }
    });
  });
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template