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.

Advertisements

Remove .PHP Extension from URL using .htaccess

We do see many PHP URLs without .php extension this can easily be achieved simply adding the following in .htaccess file.

Note: .htaccess file must be placed in the directory where PHP files are placed.

.htaccess code

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
#RewriteRule ^(.*)$ $1.php #enable it <= if / is not required after URL
RewriteRule ^(.*)/$ $1.php [L] #disable it <= if / is not required after URL
</IfModule>

After this create a file of PHP in the same folder then you can access that URL without .php extension. I have also placed slash in the end of URL if you don’t want it so simply disable last time by # comment and enable second last line by removing # before it in the above htaccess code.

Example URL with Slash:

http://localhost/tutorials/Extensionless/newpage/

Example URL without Slash:

http://localhost/tutorials/Extensionless/newpage

Leave your comments if you find this tutorial helpful.

Create a Zip File Using PHP and Download Multiple Files

In this example, i will explain how to create a zip file of multiple files using PHP and download. I will create a single file and also create a folder with name files where all files are stored.

Create a Zip File Using PHP

Download Complete Source Code

HTML:

<form name="zips" action="" method="post">
<input type="checkbox" name="files[]" value="SampleFile.pdf"/><label>PDF File</label><br />
<input type="checkbox" name="files[]" value="SampleFile.docx"/><label>Word File</label><br />
<input type="checkbox" name="files[]" value="HTML5.png"/><label>Image File</label><br />
<input type="submit" id="submit" name="createzip" value="Download All Seleted Files" >
</form>

PHP:

if(isset($_POST['files']))
{
$error = ""; //error holder
if(isset($_POST['createzip']))
{
$post = $_POST; 
$file_folder = "files/"; // folder to load files
if(extension_loaded('zip'))
{ 
// Checking ZIP extension is available
if(isset($post['files']) and count($post['files']) > 0)
{ 
// Checking files are selected
$zip = new ZipArchive(); // Load zip library 
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
{ 
 // Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($post['files'] as $file)
{ 
$zip->addFile($file_folder.$file); // Adding files into zip
}
$zip->close();
if(file_exists($zip_name))
{
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}

}
else
$error .= "* Please select file to zip ";
}
else
$error .= "* You dont have ZIP extension";
}
}

Complete Webpage:

<?php
if(isset($_POST['files']))
{
$error = ""; //error holder
if(isset($_POST['createzip']))
{
$post = $_POST; 
$file_folder = "files/"; // folder to load files
if(extension_loaded('zip'))
{ 
// Checking ZIP extension is available
if(isset($post['files']) and count($post['files']) > 0)
{ 
// Checking files are selected
$zip = new ZipArchive(); // Load zip library 
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
{ 
 // Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($post['files'] as $file)
{ 
$zip->addFile($file_folder.$file); // Adding files into zip
}
$zip->close();
if(file_exists($zip_name))
{
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}

}
else
$error .= "* Please select file to zip ";
}
else
$error .= "* You dont have ZIP extension";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create a Zip File Using PHP and Download Multiple Files</title>
</head>
<body>
<h1>Create a Zip File Using PHP and Download Multiple Files</h1>
<form name="zips" action="" method="post">
<input type="checkbox" name="files[]" value="SampleFile.pdf"/><label>PDF File</label><br />
<input type="checkbox" name="files[]" value="SampleFile.docx"/><label>Word File</label><br />
<input type="checkbox" name="files[]" value="HTML5.png"/><label>Image File</label><br />
<input type="submit" id="submit" name="createzip" value="Download All Seleted Files" >
</form>
</body>
</html>

Download Complete Source Code

Leave your comments if you find this tutorial helpful.

 

Enable Disable Submit Button If One Checkbox is Checked

This is very simple tutorial which enable submit button if at least one checkbox is checked otherwise disable submit button.

Enable Disable Submit Button

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

Demo: https://jsfiddle.net/javedfiddle/fj8r9w9v/

HTML:

<form method="post" action="">
<input class="chk" type="checkbox" name="html" value="html" />HTML<br/>
<input class="chk" type="checkbox" name="javascript" value="javascript" />JavaScript<br/>
<input class="chk" type="checkbox" name="jquery" value="jquery" />JQuery<br/><br/>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>

JavaScript:

$('#submit').prop("disabled", true);
$('input:checkbox').click(function() {
 if ($(this).is(':checked')) {
 $('#submit').prop("disabled", false);
 } else {
 if ($('.chk').filter(':checked').length < 1){
 $('#submit').attr('disabled',true);}
 }
});

Demo: https://jsfiddle.net/javedfiddle/fj8r9w9v/

Leave your comments if you find this tutorial helpful.