Home >Backend Development >PHP Tutorial >How to Retrieve MySQL Data Using jQuery AJAX and Display it on a Web Page Without Reloading?
Using jQuery AJAX to Retrieve Data from MySQL
Using AJAX (Asynchronous JavaScript and XML) with jQuery, you can retrieve data from a MySQL database and display it on a web page without reloading the entire page. To achieve this, follow these steps:
jQuery AJAX Code
In your HTML file, include the jQuery library and write the following AJAX code:
<script type="text/javascript" src="jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var response = ''; $.ajax({ type: "GET", url: "Records.php", async: false, success: function(text) { response = text; } }); alert(response); }); </script>
PHP Code
In your Records.php file, connect to the MySQL database and execute the query to retrieve the records:
$con = mysql_connect("localhost","root",""); $dbs = mysql_select_db("simple_ajax",$con); $query = "SELECT Name, Address FROM users"; $result = mysql_query($query); // Create the response in HTML format $html = ""; while ($row = mysql_fetch_array($result)) { $html .= "<tr><td>$row[Name]</td><td>$row[Address]</td></tr>"; } echo $html;
Resolving the Issue
The provided code may not be working for you because of the following reasons:
Solution
To fix these issues, modify your code as follows:
list.php
<script type="text/javascript"> $(document).ready(function() { $.ajax({ type: "GET", url: "Records.php", async: false, success: function(text) { $("#div1 h2").html(text); } }); }); </script>
Records.php
<?php $mysqli = new mysqli("localhost", "root", "", "simple_ajax"); if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } $result = $mysqli->query("SELECT Name, Address FROM users"); // Create the response in HTML format $html = ""; while ($row = $result->fetch_array(MYSQLI_ASSOC)) { $html .= "<tr><td>{$row['Name']}</td><td>{$row['Address']}</td></tr>"; } $mysqli->close(); echo $html;
With these changes, your AJAX code should successfully retrieve records from the MySQL database and display them on the web page without reloading.
The above is the detailed content of How to Retrieve MySQL Data Using jQuery AJAX and Display it on a Web Page Without Reloading?. For more information, please follow other related articles on the PHP Chinese website!