Retrieve Data From Database Without Page refresh using AJAX, PHP and Javascript

In this article, you will learn how to retrieve data from a database without refreshing the web page. This data will be retrieved on the Javascript event. As we know, Javascript is a dynamic language. It means, it can control, access and manipulate the HTML elements dynamically on the client side.

Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript

Suppose we have a "employee" table that contains an employee id and employee name and a "emp_info" table that contains whole employee information. We want to display the employee whole information on the web page based on the 'employee name'. The usual data retrieval process takes more loading time. So in the below script, we are using Ajax that load data without refreshing the page. Ajax is a technique to provide fast and dynamic web services. It updates or retrieves data asynchronously by exchanging data over the server.



Either, you can create a database name 'company' and copy paste these commands in database or you can use your existing database.

CREATE TABLE IF NOT EXISTS `employee` (
  `emp_id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(150) NOT NULL,
  `is_enabled` int(11) NOT NULL,
  PRIMARY KEY (`emp_id`)
) 

INSERT INTO `employee` (`emp_id`, `emp_name`, `is_enabled`) VALUES
(1, 'John', 1),
(2, 'Smith', 1),
(3, 'Priska', 1),
(4, 'Gaga', 1);
CREATE TABLE IF NOT EXISTS `emp_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_id` int(11) NOT NULL,
  `emp_name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `phone` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) 

INSERT INTO `emp_info` (`id`, `emp_id`, `emp_name`, `email`, `phone`) VALUES
(1, 1, 'John', This email address is being protected from spambots. You need JavaScript enabled to view it.', 234534322),
(2, 3, 'Priska', This email address is being protected from spambots. You need JavaScript enabled to view it.', 437777711),
(3, 2, 'Smith', This email address is being protected from spambots. You need JavaScript enabled to view it.', 332454277),
(4, 4, 'Gaga', This email address is being protected from spambots. You need JavaScript enabled to view it.', 229503990);

Here, we have created two files - 'index.php' and 'loademployeedata.php'. So create these two files in your working directory and copy paste these codes.



index.php

<?php
$conn = new mysqli('hostname', 'username', 'password', 'database');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
$select = "SELECT * FROM employee WHERE is_enabled = '1'";
$result = $conn->query($select);
$option = '<option value="">Select Name</option>';
while($row = $result->fetch_object()){
    $option .= '<option value="'.$row->emp_id.'">'.$row->emp_name.'</option>';
}
?>     
<html>
    <head>
        <title>Retrieve data from database using Ajax</title>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
		crossorigin="anonymous">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script type="text/javascript">
            function getData(empid, divid){
                $.ajax({
                    url: 'loademployeedata.php?empid='+empid, 
                    success: function(html) {
                        var ajaxDisplay = document.getElementById(divid);
                        ajaxDisplay.innerHTML = html;
                    }
                });
            }
        </script>
    </head>
    <body>
        <form method="post">
            <select name="empid" id="empid"  class="form-control" onchange="getData(this.value, 'displaydata')">
              <?php
                echo $option;
              ?> 
            </select>
            <div id="displaydata">
            </div>
        </form>
    </body>
</html>

In the above file, first we have written mysqli database connection code and fetched all enabled data from 'employee' table. Make sure to replace 'hostname', 'username', 'password' and 'database' with your database credentials and name. Then, we have stored all employee name in HTML select option fields using PHP.

Next, we have created an HTML form element and placed select element inside. On select element, we have added onChange() name attribute, that calls the getData() method on change the select option.

onchange="getData(this.value, 'displaydata')"

Here, this.value contains employee id and displaydata is an id of empty div. The getData() Javascript function is created in the head section of 'index.php'. This function calls the Ajax file 'loademployeedata.php' and fetches the employee information based on the passed 'empid' in url and stores the fetched data in the empty div.



loademployeedata.php

<?php
$empid = $_GET['empid'];
$conn = new mysqli('localhost', 'root', '', 'company');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
if (isset($empid)) {
    $select  = " SELECT * FROM emp_info WHERE emp_id = '$empid'";
    $result = $conn->query($select);
    echo '<table class="table table-bordered">';
    while($row = $result->fetch_object()){
        echo '<tr>'
            .'<td>'.$row->emp_name.'</td>'
            .'<td>'.$row->email.'</td>'
            .'<td>'.$row->phone.'</td>'
            .'</tr>';
    }
    echo '</table>';
}     
?>     

In the above file, we have received the 'empid' using global variable $_GET and stored in a variable $empid. Next, we have created the mysqli database connection code and fetched the employee information from 'emp_info' table. Using PHP while loop, iterates over the information and stores the data in a tabular format and this same format is rendered in the empty div that we have generated in 'index.php' page.





Related Articles

JavaScript display PDF in the browser using Ajax call
How to Retrieve Emails from Gmail using PHP IMAP
How to store Emoji character in MySQL using PHP
How to display PDF file in PHP from database
jQuery loop over JSON result after AJAX Success
Dynamically Add/Delete HTML Table Rows Using Javascript
Submit a form data without page refresh using PHP, Ajax and Javascript
PHP Server Side Form Validation
How to add google reCAPTCHA v2 in registration form using PHP
Complete HTML Form Validation in PHP




Read more articles


General Knowledge



Learn Popular Language