Ajax Drop Down Selection Data Load With PHP Amp MySQL
Ajax Drop Down Selection Data Load With PHP Amp MySQL
phpzag.com /ajax-drop-down-selection-data-load-with-php-mysql/
PHPZAG 22/1/2017
Team
In this tutorial you will learn how to create dynamic drop down selection to load data with jQuery, PHP and
MySQL. The dynamic drop down mostly used to display related data. In this tutorial we will implement drop down
of employee to show employee details on employee name selection. The drop down selection data load handled
on selection without page reload using Ajax.
The tutorial covers in very easy steps with live demo and complete demo script to download. So lets start the
coding.
1/4
Steps3: Include Bootstrap, jQuery and JavaScript Files
In this tutorial,. We have created PHP file index.php and included all necessary library files (Bootstrap, jQuery,
validation js) and CSS files in head tag. In this tutorial, we have created HTML using Bootstrap. The JavaScript
file getData.js handle drop down change event and make Ajax request to load data.
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-
theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">
</script>
<script type="text/javascript" src="script/getData.js"></script>
2/4
$(document).ready(function(){
// code to get all records from table via select
box
$("#employee").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url: 'getEmployee.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
$("#heading").show();
$("#no_records").hide();
$("#emp_name").text(employeeData.employee_name);
$("#emp_age").text(employeeData.employee_age);
$("#emp_salary").text(employeeData.employee_salary);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
})
});
Now finally in getEmployee.php, we will get employee details from MySQL database table and return data as
JSON using json_encode.
<?php
include_once("db_connect.php");
if($_REQUEST['empid']) {
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee
WHERE id='".$_REQUEST['empid']."'";
$resultset = mysqli_query($conn, $sql) or die("database error:".
mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
You can view the live demo from the Demo link and can download the script from the Download link below.
Demo
3/4
error
4/4