As we have discussed earlier about how to delete data using AJAX. Now we are going to discuss about how to fetch or retrieve data using in php with use of MySQL. AJAX is mixed technology with JavaScript and XML which is used for loading data without reload or refresh of page. Let us see how to fetch data without reloading of a webpage. Let us see the example.
Table of Contents
Demo
Following are are the necessary files for fetching dat using AJAX.
Database
DB name= phpcluster //Database name as require
Table name = deletedata //table name as require
Files
Index.php
Fetchdata.php
jquery-1.3.2.js
Now see the details of files which are as mention below:
Index.php
<html> <body> <h3 align="center">Manage Records</h3> <table border="1" align="center"> <tr> <td> <input type="button" id="display" value="Display All Data" /> </td> </tr> </table> <div id="responsecontainer" align="center"> </div> </body> </html>
AJAX Script
<script type="text/javascript" src="jquery-1.3.2.js"> </script> <script type="text/javascript"> $(document).ready(function() { $("#display").click(function() { $.ajax({ //create an ajax request to fetchdata.php type: "GET", url: "fetchdata.php", dataType: "html", //expect html to be returned success: function(response){ $("#responsecontainer").html(response); //alert(response); } }); }); }); </script>
Above page is index.php and we are putting this AJAX code in it but here I am displaying AJAX Script separately to get easily.
Fetchdata.php
<?php $connection = mysql_connect('localhost', 'root', ''); $db = mysql_select_db('phpcluster', $connection); $result=mysql_query("select * from deletedata"); echo "<table border='1' > <tr> <td align=center> <b>ID</b></td> <td align=center><b>Name</b></td>"; while($data = mysql_fetch_row($result)) { echo "<tr>"; echo "<td align=center>$data[0]</td>"; echo "<td align=center>$data[1]</td>"; echo "</tr>"; } echo "</table>"; ?>
Now to see the retrieved data using AJAX please click on Display data button and get your all records without reloading a page.