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


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.

function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
} 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;

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

while($row = mysql_fetch_array($result))
<option value="<?php echo $name;?>"><?php echo $name;?></option>
<div id="txtHint"><b>Patient info will be listed here...</b></div>


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

table {
width: 100%;
border-collapse: collapse;
table, td, th {
border: 1px solid black;
padding: 5px;
th {text-align: left;}
$q =$_GET['q'];
$con = mysqli_connect('localhost','root','');
$sql="SELECT * FROM sample WHERE Name='".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<th>Patient name</th>
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>";



Support us by Sharing