etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

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 an "employee" table that contains an employee id and employee name and a "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 that loads 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 a select element inside. On the select element, we have added onChange() name attribute that calls the getData() method on changing the select option.

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

Here, this.value contains employee id and displaydata is an 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 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 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 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



Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple pagination in PHP with MySQL
-----------------
How to generate QR Code in PHP
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
PHP MYSQL Advanced Search Feature
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
jQuery File upload progress bar with file size validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
To check whether a year is a leap year or not in php
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
Simple PHP File Cache
-----------------
PHP User Authentication by IP Address
-----------------
Calculate the distance between two locations using PHP
-----------------
PHP Secure User Registration with Login/logout
-----------------
Polling system using PHP, Ajax and MySql
-----------------
How to print specific part of a web page in javascript
-----------------
Detect Mobile Devices in PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
Simple way to send SMTP mail using Node.js
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
CSS Simple Menu Navigation Bar
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Date Timestamp Formats in PHP
-----------------
PHP Programming Error Types
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
PHP Getting Document of Remote Address
-----------------
How to display PDF file in web page from Database in PHP
-----------------
File Upload Validation in PHP
-----------------
PHP FTP Connection and File Handling
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.