Retrieve data from Database without page refresh using AJAX, PHP and JavaScript

In this post, you will learn how to retrieve data from a database without refreshing the web page using AJAX, PHP, and JavaScript.





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 an "employee" table that contains employee id, employee name, and an "emp_info" table that contains the whole employee information. We want to display the employee's whole information on the website's 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 to load data without refreshing the page. Ajax is a technique for providing fast and dynamic web services. It updates or retrieves data asynchronously by exchanging data over the server.



Either you can create a database named 'company' and copy and paste these commands into it, 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'.





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 the MySQLi database connection code and fetched all the enabled data from the 'employee' table. Make sure to replace 'hostname', 'username', 'password', and 'database' with your database credentials and name. Then, we stored all employee names in HTML select option fields using PHP.





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

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

Here, this.value contains the employee id, and displaydata is the id of an 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 the 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 a global variable $_GET and stored it in a variable $empid. Next, we created the MySQLi database connection code and fetched the employee information from the 'emp_info' table. Using the PHP while loop, the program iterates over the information and stores the data in a tabular format. The same format is rendered in the empty div that we have generated in the 'index.php' page.





Related Articles

PHP remove last character from string
PHP calculate percentage of total
Convert stdclass object to array PHP
PHP sanitize input for MySQL
Insert image in database using PHP
Download and open PDF file using Ajax
Retrieve Your Gmail Emails Using PHP and IMAP
How to retrieve data from database without refreshing page
Print specific part of webpage
Store Emoji character in MySQL using PHP
PHP Display PDF file from Database
Jquery ajax loop through data
Dynamically add/remove rows in html table using jquery
Submit form without page refresh using javascript
PHP Form Validation Tutorial
Google reCAPTCHA v3 PHP example
HTML Form Validation in PHP
How to display doc file in PHP from database
PHP upload multiple files
How to fetch data from database in php




Read more articles


General Knowledge



Learn Popular Language