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 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

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




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


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 27

    Best AI Startups In India

    Artificial Intelligence is a process of making an intelligent computer machine that does tasks intelligently...

  • Jan 23

    Most in demand programming languages for 2019

    In this article, we have mentioned the analyzed results of the most in demand programming language for 2019...

  • Jan 15

    Web Robots

    Web robots is an internet robot or simply crawlers, or spiders and do not relate this with hardware robots...

  • Jan 12

    Most in demand NoSQL databases software for 2019

    In this article, we have mentioned the analyzed result of most in demand NoSQL database softwares for 2019...

  • Jan 10

    Kotlin : Android App Development Choice

    Kotlin is a general-purpose open-source programming language. It runs on the JVM and its syntax is much like Java...

Follow us

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


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