How to retrieve data from database in php using ajax

15/04/2017   04:14:54 PM

Hello friends, in this tutorial I will explain how to retrieve data from mysql database using php and ajax. We will fetch data from database without refreshing the webpage. This step by step tutorial will make the whole process very easy and understandable for you.

What is AJAX?

AJAX =Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX just uses a combination of:

A browser built-in XMLHttpRequest object (to request data from a web server)

JavaScript and HTML DOM (to display or use the data)

1) Create Database & Table

  • First create a database then create table inside your database. I have created a hospital database inside PatientHistroy table created as you can see in the below image

retrive_data_mysql_php_ajax

2) Create HTML Page

  • Now we will create a simple html page with one dropdown. In that we will see the Patient name. As per Patient name display data in table format.

  • You can use the following html code to create your page. Copy and save it as index.html in your project folder.

<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>

 
<form>
<select name="Patientname" onchange="showUser(this.value)">
<option value="">Select name</option>
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("sampledb", $con);
 
$result = mysql_query("SELECT * FROM sample");

while($row = mysql_fetch_array($result))
{
$name=$row['Name'];
?>
<option value="<?php echo $name;?>"><?php echo $name;?></option>
<?php
}
mysql_close($con);
?>
</select>
</form>
<br>
<div id="txtHint"><b>Patient info will be listed here...</b></div>

 

3) Create getuser.php page and add the following code

<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
<?php
$q =$_GET['q'];
$con = mysqli_connect('localhost','root','');
mysqli_select_db($con,"sampledb");
$sql="SELECT * FROM sample WHERE Name='".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Patient name</th>
<th>Age</th>
<th>Disease</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Disease'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

Output

                   

Support us by Sharing