Dynamic Dependent Select Box using jQuery and Ajax

We often see dependent select box on the websites, when parent changes, its child select box automatically changes. Today i will explain that how it works, i will use example of country and cities, when someone select any country, cities of that country will be displayed automatically. Let me give you a quick review of this tutorial, all countries are fetching from database table name county, when someone select any country then it fetches the cities of that country without refresh or reload the page this is the power of Ajax which helps to retrieve data from database without refresh page.

Download Complete Source Code

Dynamic Dependent Select Box using jQuery and Ajax

Steps to Create Dynamic Dependent Select Box using jQuery and Ajax

  1. Create a Database
  2. Create Two Tables of County and City
  3. Create a Database Connection
  4. Create Index File with Ajax
  5. Create Action PHP File

1. Create a Database

Create a database with name parent_child_select. Simply execute the following query.

CREATE DATABASE parent_child_select;

2. Create Two Tables of County and City

Create two tables of county and city with name country and city. Simply execute the following queries. Or you can also import the attached sql file to create table with data which is available in download file.

CREATE TABLE IF NOT EXISTS `country` (
 `country_id` int(11) NOT NULL AUTO_INCREMENT,
 `country_name` varchar(50) NOT NULL,
 PRIMARY KEY (`country_id`)
 );

CREATE TABLE IF NOT EXISTS `city` (
 `city_id` int(11) NOT NULL AUTO_INCREMENT,
 `city_name` varchar(50) NOT NULL,
 `country_id` varchar(50) NOT NULL,
 PRIMARY KEY (`city_id`)
 );

3. Create a Database Connection

Simply create a file with name db.php and paste the below code there.

$hostname = "localhost";
$user = "root";
$password = "";
$database = "parent_child_select";
$bd = mysql_connect($hostname, $user, $password) 
or die("DB Connection Failed!");
mysql_select_db($database, $bd) or die("DB Connection Failed!");

4. Create Index File with Ajax

Create a file with name index.php and paste the below code there. I will add the Ajax code in the footer of this file.

<html>
<head>
<title>Dynamic Dependent Select Box using jQuery and Ajax</title>
</head>
<body>
<div>
<label>Country :</label><select name="country" class="country">
<option selected="selected" value="0">Select Country</option>
<?php
include('db.php');
$sql=mysql_query("select * from country");
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
} ?>
</select><br/><br/>
<label>City :</label><select name="city" class="city">
<option selected="selected">Select City</option>
</select>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var id_String = 'id='+ id;

$.ajax
({
type: "POST",
url: "ajax_cities.php",
data: id_String,
cache: false,
success: function(citydata)
{
$(".city").html(citydata);
} 
});

});
});
</script>
</body>
</html>

5. Create Action PHP File

Create a file with name ajax_cities.php and paste the below code there.

include('db.php');
if($_REQUEST['id'])
{
$id=$_REQUEST['id'];
if($id==0){echo "<option>Select City</option>";}else{
$sql=mysql_query("select * from city where country_id='$id'");
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}
}

Download Complete Source Code

Leave your comments if you find this tutorial helpful.

Allow Only Logged in Users to View Files

Today i will explain how to allow only logged in users to view uploaded files using PHP, for this we need a logged in user, i have already wrote tutorial how to create simple user registration and login script in PHP and MySQL, in this tutorial i will upload file using PHP and save that file to our directory/folder, also insert record of uploaded file into table of our database. In the admin dashboard, i also placed view uploaded file option where only logged in user can view and delete uploaded files, if someone try to copy URL of specific file and open it without log in to your website then file will not be opened. I have also recently wrote tutorial how to insert, view, edit and delete record from database using PHP and MySQL, if you don’t know how to do it then i advise you first read it. In know you are thinking why am i telling you about my recent tutorials, this is because we must have them to implement this restriction.

Download Complete Source Code

View Uploaded PDF Files

Steps to Allow Access Only Logged in Users to View Files

Now lets come to our actual tutorial, i assume that you already created all files which was created in Insert, View, Edit and Delete Record from Database Using PHP and MySQL, you must have it to implement restriction that only logged in users can view uploaded files, follow the below steps.

  1. Create Another Table for Uploaded File Records
  2. Update Dashboard File
  3. Create Upload Page
  4. Create View Uploaded  File Page
  5. Create a folder name upload and create another file in this folder with name viewpdf.php, upload is a folder where all uploaded files will be saved.
  6. Create Delete File Page

1. Create Another Table for Uploaded File Records

Execute the below query in SQL

CREATE TABLE IF NOT EXISTS `filetable` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `trn_date` datetime NOT NULL,
 `filetitle` varchar(50) NOT NULL,
 `filename` varchar(50) NOT NULL,
 PRIMARY KEY (`id`)
 );

2. Update Dashboard Page

Update a dashboard.php just by paste the below code in it.

<?php 
require('db.php');
include("auth.php"); //include auth.php file on all secure pages ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dashboard - View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Welcome to Dashboard.</p>
<p><a href="index.php">Home</a><p>
<p><a href="insert.php">Insert New Record</a></p>
<p><a href="view.php">View Records</a><p>
<p><a href="upload.php">Upload File</a><p>
<p><a href="viewfiles.php">View Files</a><p>
<p><a href="logout.php">Logout</a></p>
</div>
</body>
</html>

3. Create Upload Page

Create a page with name upload.php and paste the below code in it. I have also restricted only PDF file, this means only PDF files can be uploaded, this will be check extension on client side before upload file using jQuery.

Note: Don’t forget to include the jQuery library in the header or footer.

<?php 
require('db.php');
include("auth.php"); //include auth.php file on all secure pages
$uploadstatus = "";
if(isset($_REQUEST['filetitle']))
{
$trn_date = date("Y-m-d H:i:s");
$filetitle =$_REQUEST['filetitle'];
$target_dir = "upload/"; // Where the file is going to be placed
$path = pathinfo($_FILES['upload_file']['name']);
$filename = $path['filename'];
$ext = $path['extension'];
$temp_name = $_FILES['upload_file']['tmp_name'];
$pathfilenameext= $target_dir.$filename.".".$ext;

// Check if file already exists
if (file_exists($pathfilenameext)) {
 $uploadstatus = "Sorry, file already exists.";
 }
else 
 {
 move_uploaded_file($temp_name,$pathfilenameext);
 $uploadstatus = "File Uploaded Successfully.";
 $ins_query="insert into filetable(`trn_date`,`filetitle`,`filename`)values('$trn_date', '$filetitle', '$filename')";
 mysql_query($ins_query) or die(mysql_error());
 }
}
?>
<html>
<head>
<title>Upload File Using PHP and Save in Folder</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="dashboard.php">Dashboard</a> | <a href="viewfiles.php">View Files</a> | <a href="logout.php">Logout</a></p>
<h1>Upload File</h1>
<form name="form" method="post" action="" enctype="multipart/form-data" >
<input type="text" name="filetitle" placeholder="Enter File Title:" required /><br /><br />
<input type="file" name="upload_file" id="upload_file" /><br /><br />
<p id="error" style="display:none; color:#FF0000;">File format should be PDF.</p>
<input type="submit" name="submit" value="Upload" />
</form>
<p style="color:#FF0000;"><?php echo $uploadstatus; ?></p> 
</div>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$('input[type="submit"]').prop("disabled", true);
$('#upload_file').bind('change', function() {
var ext = $('#upload_file').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf','PDF']) == -1)
{ $('#error').slideDown("slow"); } else
{$('#error').slideUp("slow"); $('input:submit').attr('disabled',false);}
});
</script>
</body>
</html>

Upload File

4. Create View Uploaded File Page

Create a page with name viewfiles.php and paste the below code in it. In this file only logged in user can view and delete file, also note that i included a confirm function onclick event, so that when user click on delete button, it should ask that “Are you sure?” if OK is pressed, file will be deleted otherwise not. If user want to view file so simply click on file title (these files only accessible for logged in users) you can confirm it just by copying the opened file URL and open it another browser window.

<?php 
require('db.php');
include("auth.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>View Uploaded PDF Files</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="dashboard.php">Dashboard</a> | <a href="upload.php">Upload New File</a> | <a href="logout.php">Logout</a></p>
<h2>View Uploaded PDF Files</h2>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr><th><strong>S.No</strong></th><th><strong>File Title</strong></th><th><strong>Delete</strong></th></tr>
</thead>
<tbody>
<?php
$count=1;
$sel_query="Select * from filetable;";
$result = mysql_query($sel_query);
while($row = mysql_fetch_assoc($result)) { ?>
<tr><td align="center"><?php echo $count; ?></td><td align="center"><a href="upload/viewpdf.php?file=<?php echo $row["filename"]; ?>.pdf" target="_new"><?php echo $row["filetitle"]; ?></a></td><td align="center"><a href="deletefile.php?id=<?php echo $row["id"]; ?>&filename=<?php echo $row["filename"]; ?>" onclick="return confirm('Are you sure?')">Delete</a></td></tr>
<?php $count++; } ?>
</tbody>
</table>
</div>
</body>
</html>

View Uploaded PDF Files

5. Create a Folder with name Upload & Create Another File in this folder with name viewpdf.php

Create a page with name viewpdf.php and paste the below code in it. (Make sure this file should be placed into Upload directory) This is the main file which restrict that only logged in user is viewing file, it simply check is user session is set, if yes then allow to view file.

<?php
session_start();
if(!isset($_SESSION["username"])){
header("location: ../login.php");
}
else{
if (isset($_GET['file'])) {
$file = $_GET['file'];
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-Type: application/pdf');
header("Content-Disposition: inline; filename=\"$file\"");
readfile($file);
}
} else {
header("Location: ../index.php");
}
}
?>

6. Create Delete File Page

Create a page with name deletefile.php and paste the below code in it. This file not only delete file record from DB table but also delete file from directory as well.

<?php 
require('db.php');
$id=$_REQUEST['id'];
$filename=$_REQUEST['filename'];
$query = "DELETE FROM filetable WHERE id=$id"; 
$result = mysql_query($query) or die ( mysql_error());
$target = "upload/".$filename.".pdf";
if (file_exists($target)) {
 unlink($target); // Delete File From Directory
}
header("Location: viewfiles.php"); 
?>

Download Complete Source Code

Leave your comments if you find this tutorial helpful.