I used this code when I have a small list of records (e.g. authors or categories) that can be picked using a drop-down list and then, I want to load the related information instantly without refreshing the page. So in this post, we are going to code that does:
- A drop down list with small number of names or authors
- When a user selected an item from the drop down, it will load the related data below it.
Download code and live demo here:
We are going to use 4 files only, see below:
1. js/jquery-1.9.1.min.js - our favorite JavaScript library.
2. dbConnect.php - so that we can connect to the database users table
3. index.php - this will show the users drop-down list, records are from the database users table.
<html>
<head>
<title>CodeOfaNinja.com - Loading Data With PHP, jQuery onChange() and load()</title>
<style>
body{
font-family:arial,sans-serif;
}
select{
margin:0 0 10px 0;
padding:10px;
}
td {
background-color:#e8edff;
padding: 10px;
}
</style>
</head>
<body>
<?php
// connect to database
include"dbConnect.php";
// retrieve list of users and put it in the select box
$query="SELECT id, firstname, lastname, username FROM users";
$stmt=$con->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num=$stmt->rowCount();
// make sure there are records on the database
if($num>0){
// this will create selec box / dropdown list with user records
echo"<select id='users'>";
// make a default selection
echo"<option value='0'>Select a user...</option>";
while ($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo"<option value='{$id}'>{$firstname} {$lastname}</option>";
}
echo"</select>";
}
// if no user records
else{
echo"<div>No records found</div>";
}
// this is where the related info will be loaded
echo"<div id='userInfo'></div>";
?>
<scriptsrc="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$("#users").change(function(){
// get the selected user's id
var id =$(this).find(":selected").val();
// load it in the userInfo div above
$('#userInfo').load('data.php?id='+ id);
});
});
</script>
</body>
</html>
4. data.php - this contains the query and will show the table with information related to the selected drop-down item.
<?php
include'dbConnect.php';
try {
// prepare query
$query="select
firstname, lastname, username
from
users
where
id = ?";
$stmt=$con->prepare( $query );
// this is the first question mark above
$stmt->bindParam(1, $_REQUEST['id']);
// execute our query
$stmt->execute();
// store retrieved row to a variable
$row=$stmt->fetch(PDO::FETCH_ASSOC);
// values to fill up our table
$firstname=$row['firstname'];
$lastname=$row['lastname'];
$username=$row['username'];
// our table
echo"<table>";
echo"<tr>";
echo"<td>Firstname: </td>";
echo"<td>{$firstname}</td>";
echo"</tr>";
echo"<tr>";
echo"<td>Lastname: </td>";
echo"<td>{$lastname}</td>";
echo"</tr>";
echo"<tr>";
echo"<td>Username: </td>";
echo"<td>{$username}</td>";
echo"</tr>";
echo"</table>";
}catch(PDOException$exception){
// to handle error
echo"Error: ".$exception->getMessage();
}
?>
You may have the sample MySQL table and data below:
CREATETABLEIF NOT EXISTS `users` (
`id`int(11) NOT NULL AUTO_INCREMENT,
`firstname`varchar(32) NOT NULL,
`lastname`varchar(32) NOT NULL,
`username`varchar(32) NOT NULL,
`password`varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `users`
--
INSERT INTO`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES
(1, 'John', 'Doe', 'johnny', 'john'),
(2, 'Albert', 'Minston', 'albert', 'albert');