Retrieving Data from MySQL Using jQuery Ajax
In order to retrieve data from a MySQL database using jQuery Ajax, it is essential to follow these steps:
1. Create an Ajax Request:
Utilize the $.ajax() function to establish an Ajax request. Specify the type (GET/POST), URL (where to send the request), and dataType (expected response format). Upon receiving a successful response, the success function will be executed.
2. Establishing a MySQL Connection:
For MySQL connectivity, use the mysqli extension. Establish a connection using mysqli_connect().
3. Executing Database Queries:
Run a query to fetch data from the MySQL table using the mysqli_query() function. This query will be responsible for extracting the desired records.
4. Displaying Retrieved Data:
Use a loop to iterate through the result set and display the data in a structured manner. Consider using a table for data representation.
Sample Code:
<script type="text/javascript"> $(document).ready(function() { $("#display").click(function() { $.ajax({ type: "GET", url: "display.php", dataType: "html", success: function(response) { $("#responsecontainer").html(response); } }); }); }); </script> <body> <button>
<?php $con = mysqli_connect("localhost", "root", ""); mysqli_select_db($con, "samples"); $result = mysqli_query($con, "SELECT * FROM student"); echo "<table border='1'>"; echo "<tr><th>Roll No</th><th>Name</th><th>Address</th><th>Stream</th><th>Status</th></tr>"; while ($row = mysqli_fetch_row($result)) { echo "<tr>"; foreach ($row as $value) { echo "<td>$value</td>"; } echo "</tr>"; } echo "</table>"; ?>
By following these instructions and utilizing the provided code snippets, you can successfully retrieve and display data from a MySQL database using jQuery Ajax.
The above is the detailed content of How to Retrieve MySQL Data Using jQuery Ajax?. For more information, please follow other related articles on the PHP Chinese website!