Codeigniter Tutorials
- What is codeigniter?
- Application_Architecture
- MVC Architecture
- HMVC Architecture
- Codeigniter Configuration
- Remove index.php from url in codeigniter
- MVC Concept
- View
- Alternate PHP Syntax for View Files
- Routing
- Codeigniter URL
- Get Current URL
- Previous page URL get
- Seo Friendly URL
- Slug Create in codeigniter
- What is _remap() function
- Remove controller name from url in codeigniter
- Codeigniter Controller Class
- Class Constructor
- GET $ POST method in Codeigniter
- Models
- Basepath, Apppath, FCPATH
- URI Segment
- Page Redirect
- Helper class
- Custom Helper class
- Form Helper
- Common Helper Functions
- Common Function
- Array Problems
- Call controller in Helper
- Add active class to menu using Helper class
- Custom Library
- Custom Library Example
- when to use get_instance()
- Codeigniter Hook
- how to work inline css in codeigniter
- Custom 404 page
- 404 custom error page
- Create custom config file in codeigniter
- How to set and get config item value
- How to Speed Up CodeIgniter App?
- Codeigniter Functions
- Session
- cookies
- How to Set & Get Tempdata in Codeigniter
- flash messages in Codeigniter
- Flashdata
- Encryption and Decryption In CodeIgniter
- Codeigniter security
- csrf token form security
- Password Hashing
- Form Validation
- Custom Validation
- Registration Form with validation
- Server Side Form Validation
- Validate Select Option Field
- Date Format Validation
- Date Format change in codeigniter
- Date Functions
- DOB Validation
- CI CRUD
- User SignUp
- User Login
- User Logout
- Login Account
- Login form with RememberMe
- Login Form with session
- User change password
- Change Password with Callback Validation to Check Old Password
- Forgot password
- Reset password
- Insert data in database
- Fetch data from database
- Update data in database
- Delete data in database
- File Upload
- Image Upload with resize Image
- Upload Multiple file and images
- Upload Multiple images with CRUD
- File and image update
- Upload Image Using Ajax.
- Email Send
- Email Send Using Email library
- Email Send Using SMTP Gmail
- Notification send
- store data in json format in DB
- Json parse
- Fetch data Using Ajax with Json data
- How to Show data Using Ajax with Json parse
- Get JSON Data from PHP Script using jQuery Ajax
- Insert data Using Ajax
- Submit data Using Ajax with form validation
- How to show data Using Ajax in codeigniter
- Insert & Update Using Ajax
- Registration Form With Validation Using Ajax in codeigniter
- Delete data Using Ajax Confirmation
- Delete All data Using checkbox selection
- Ajax CSRF Token
- Ajax Post
- Ajax serverside form validation
- Contact form using AJAX with form validation
- DataTable Using Ajax dynamically
- DataTables pagination using AJAX with Custom filter
- DataTables AJAX Pagination with Search and Sort in codeigniter
- DataTables in Codeigniter using Ajax
- Ajax Custom Serarch
- Ajax Live Data Search using Jquery PHP MySql
- Ajax Custom Serarch and sorting in datatable
- Dynamic Search Using Ajax
- Autocomplete using jquery ajax
- Jquery Ajax Autocomplete Search using Typeahead
- Dynamic Dependent Dropdown Using Ajax
- Dynamic Dependent Dropdown list Using Ajax
- Dynamic Dependent Dropdown in codeigniter using Ajax
- ajax username/email availability check using JQuery
- Check Email Availability Using Ajax
- Data Load on mouse scroll
- Ajax CI Pagination
- Pagination in codeigniter
- Ajax Codeigniter Pagination
- email exists or not using ajax with json
- CRUD using AJAX With Modal popup in CI
- Add / Show Data on modal popup using Ajax
- Modal popup Validation using Ajax
- Data show on Modal popup Using Ajax
- Add / Remove text field dynamically using jquery ajax
- How to Add/Delete Multiple HTML Rows using JavaScript
- Delete Multiple Rows using Checkbox
- Multiple Checkbox value
- Form submit using jquery Example
- REST & SOAP API
- Multi-Language implementation in CodeIgniter
- How to pass multiple array in view
- Captcha
- create zip file and download
- PhpOffice PhpSpreadsheet Library (Export data in excel sheet)
- data export in excel sheet
- Excel File generate in Codeigniter using PHPExcel
- Dompdf library
- tcpdf library
- Html table to Excel & docs download
- CI Database Query
- Database Query
- SQL Injection Prevention
- Auth Model
- Join Mysql
- Tree View in dropdown option list
- OTP Integration in codeigniter
- curl post
- download file using curl
- Sweet Alert
- Sweet alert Delete & Success
- Log Message in Codeigniter
- Menu & Submenu show dynamically
- Set Default value in input box
- Cron Jobs
- Stored Procedure
- Display Loading Image when AJAX call is in Progress
- Send SMS
- IP Address
- Codeigniter Tutorialspoint
- Website Link
- How To Create Dynamic Xml Sitemap In Codeigniter
- Paypal Payment Integration
- Get Latitude and Longitude From Address in Codeigniter Using google map API
- How To Create Simple Bar Chart In Codeigniter Using AmCharts?
- dynamic Highcharts in Codeigniter
- Barcode in Codeigniter
- Codeigniter Interview Questions
- Project
Home » Codeigniter »
Dynamic dependent Dropdown using jquery ajax.
View File
<html>
<head>
<title>Codeigniter Dynamic Dependent Select Box using Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style>
.box
{
width:100%;
max-width: 650px;
margin:0 auto;
}
</style>
</head>
<body>
<div class="container box">
<br />
<br />
<h3 align="center">Codeigniter Dynamic Dependent Select Box using Ajax</h3>
<br />
<div class="form-group">
<select name="country" id="country" class="form-control input-lg">
<option value="">Select Country</option>
<?php
foreach($country as $row)
{
echo '<option value="'.$row->country_id.'">'.$row->country_name.'</option>';
}
?>
</select>
</div>
<br />
<div class="form-group">
<select name="state" id="state" class="form-control input-lg">
<option value="">Select State</option>
</select>
</div>
<br />
<div class="form-group">
<select name="city" id="city" class="form-control input-lg">
<option value="">Select City</option>
</select>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#country').change(function(){
var country_id = $('#country').val();
if(country_id != '')
{
$.ajax({
url:"<?php echo base_url(); ?>dynamic_dependent/fetch_state",
method:"POST",
data:{country_id:country_id},
success:function(data)
{
$('#state').html(data);
$('#city').html('<option value="">Select City</option>');
}
});
}
else
{
$('#state').html('<option value="">Select State</option>');
$('#city').html('<option value="">Select City</option>');
}
});
$('#state').change(function(){
var state_id = $('#state').val();
if(state_id != '')
{
$.ajax({
url:"<?php echo base_url(); ?>dynamic_dependent/fetch_city",
method:"POST",
data:{state_id:state_id},
success:function(data)
{
$('#city').html(data);
}
});
}
else
{
$('#city').html('<option value="">Select City</option>');
}
});
});
</script>
Controller
File Name :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Dynamic_dependent extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Auth_model');
}
function index()
{
$data['country'] = $this->Auth_model->fetch_country();
$this->load->view('dynamic_dependent', $data);
}
function fetch_state()
{
if($this->input->post('country_id'))
{
echo $this->Auth_model->fetch_state($this->input->post('country_id'));
}
}
function fetch_city()
{
if($this->input->post('state_id'))
{
echo $this->Auth_model->fetch_city($this->input->post('state_id'));
}
}
}
Model
File Name :- Auth_model.php
function fetch_country()
{
$this->db->order_by("country_name", "ASC");
$query = $this->db->get("country");
return $query->result();
}
function fetch_state($country_id)
{
$this->db->where('country_id', $country_id);
$this->db->order_by('state_name', 'ASC');
$query = $this->db->get('state');
$output = '<option value="">Select State</option>';
foreach($query->result() as $row)
{
$output .= '<option value="'.$row->state_id.'">'.$row->state_name.'</option>';
}
return $output;
}
function fetch_city($state_id)
{
$this->db->where('state_id', $state_id);
$this->db->order_by('city_name', 'ASC');
$query = $this->db->get('city');
$output = '<option value="">Select City</option>';
foreach($query->result() as $row)
{
$output .= '<option value="'.$row->city_id.'">'.$row->city_name.'</option>';
}
return $output;
}
Table
CREATE TABLE `country` (
`country_id` int(11) NOT NULL,
`country_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `country` (`country_id`, `country_name`) VALUES
(1, 'USA'),
(2, 'Canada'),
(3, 'Australia'),
(4, 'India');
CREATE TABLE `state` (
`state_id` int(11) NOT NULL,
`country_id` int(11) NOT NULL,
`state_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 1, 'New York'),
(2, 1, 'Alabama'),
(3, 1, 'California'),
(4, 2, 'Ontario'),
(5, 2, 'British Columbia'),
(6, 3, 'New South Wales'),
(7, 3, 'Queensland'),
(8, 4, 'Karnataka'),
(9, 4, 'Telangana');
CREATE TABLE `city` (
`city_id` int(11) NOT NULL,
`state_id` int(11) NOT NULL,
`city_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `city` (`city_id`, `state_id`, `city_name`) VALUES
(1, 1, 'New York city'),
(2, 1, 'Buffalo'),
(3, 1, 'Albany'),
(4, 2, 'Birmingham'),
(5, 2, 'Montgomery'),
(6, 2, 'Huntsville'),
(7, 3, 'Los Angeles'),
(8, 3, 'San Francisco'),
(9, 3, 'San Diego'),
(10, 4, 'Toronto'),
(11, 4, 'Ottawa'),
(12, 5, 'Vancouver'),
(13, 5, 'Victoria'),
(14, 6, 'Sydney'),
(15, 6, 'Newcastle'),
(16, 7, 'City of Brisbane'),
(17, 7, 'Gold Coast'),
(18, 8, 'Bangalore'),
(19, 8, 'Mangalore'),
(20, 9, 'Hydrabad'),
(21, 9, 'Warangal');
Example 2 : Controller
public function index()
{
$this->load->model('model');
$result['list']=$this->model->getCountry();
$this->load->view('top');
$this->load->view('index',$result);
$this->load->view('footer');
}
public function loadData()
{
$loadType=$_POST['loadType'];
$loadId=$_POST['loadId'];
$this->load->model('model');
$result=$this->model->getData($loadType,$loadId);
$HTML="";
if($result->num_rows() > 0){
foreach($result->result() as $list){
$HTML.="<option value='".$list->id."'>".$list->name."</option>";
}
}
echo $HTML;
}
Model
function getCountry()
{
$this->db->select('id,country_name');
$this->db->from('country');
$this->db->order_by('country_name', 'asc');
$query=$this->db->get();
return $query;
}
function getData($loadType,$loadId)
{
if($loadType=="state"){
$fieldList='id,state_name as name';
$table='state';
$fieldName='country_id';
$orderByField='state_name';
}else{
$fieldList='id,city_name as name';
$table='city';
$fieldName='state_id';
$orderByField='city_name';
}
$this->db->select($fieldList);
$this->db->from($table);
$this->db->where($fieldName, $loadId);
$this->db->order_by($orderByField, 'asc');
$query=$this->db->get();
return $query;
}
javascript code
function selectState(country_id){
if(country_id!="-1"){
loadData('state',country_id);
$("#city_dropdown").html("<option value='-1'>Select city</option>");
}else{
$("#state_dropdown").html("<option value='-1'>Select state</option>");
$("#city_dropdown").html("<option value='-1'>Select city</option>");
}
}
function selectCity(state_id){
if(state_id!="-1"){
loadData('city',state_id);
}else{
$("#city_dropdown").html("<option value='-1'>Select city</option>");
}
}
function loadData(loadType,loadId){
var dataString = 'loadType='+ loadType +'&loadId='+ loadId;
$("#"+loadType+"_loader").show();
$("#"+loadType+"_loader").fadeIn(400).html('Please wait... <img src="image/loading.gif" />');
$.ajax({
type: "POST",
url: "loadData",
data: dataString,
cache: false,
success: function(result){
$("#"+loadType+"_loader").hide();
$("#"+loadType+"_dropdown").html("<option value='-1'>Select "+loadType+"</option>");
$("#"+loadType+"_dropdown").append(result);
}
});
}
table
CREATE TABLE IF NOT EXISTS `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(500) NOT NULL
)
CREATE TABLE IF NOT EXISTS `state` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_id` int(11) NOT NULL,
`state_name` varchar(500) NOT NULL
)
CREATE TABLE IF NOT EXISTS `city` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_id` int(11) NOT NULL,
`city_name` varchar(500) NOT NULL
)
Example 2:-
CREATE TABLE `state` (
`id` int(11) NOT NULL,
`name` varchar(155) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
City Table :-
CREATE TABLE `cities` (
`id` int(11) NOT NULL,
`state_id` int(12) NOT NULL,
`name` varchar(155) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Controller :-
public function index() {
$states = $this->db->get("state")->result();
$this->load->view('myform', array('states' => $states ));
}
public function myformAjax($id) {
$result = $this->db->where("state_id",$id)->get("cities")->result();
echo json_encode($result);
}
View :- myform.php
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Dynamic Dependent Dropdown Example </title>
<script src="http://itechxpert.in/plugin/jquery.js"></script>
<link rel="stylesheet" href="http://itechxpert.in/plugin/bootstrap-3.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Select State and get bellow Related City</div>
<div class="panel-body">
<div class="form-group">
<label for="title">Select State:</label>
<select name="state" class="form-control" style="width:350px">
<option value="">--- Select State ---</option>
<?php
foreach ($states as $key => $value) {
echo "<option value='".$value->id."'>".$value->name."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label for="title">Select City:</label>
<select name="city" class="form-control" style="width:350px">
</select>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/myform/ajax/'+stateID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
</script>
</body>
</html>
Example
Example 3 :-
<?php
//Table structure for table `countries`
CREATE TABLE `countries` (
`id` int(11) NOT NULL,
`sortname` varchar(3) NOT NULL,
`name` varchar(150) NOT NULL,
`slug` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `countries`
ADD PRIMARY KEY (`id`);
ALTER TABLE `countries`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
//Table structure for table `states`
CREATE TABLE `states` (
`id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`country_id` int(11) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `states`
ADD PRIMARY KEY (`id`);
ALTER TABLE `states`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
//Table structure for table `cities`
CREATE TABLE `cities` (
`id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`state_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `cities`
ADD PRIMARY KEY (`id`);
ALTER TABLE `cities`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
?>
Model
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Site extends CI_Model {
private $_countryID;
private $_stateID;
// set country id
public function setCountryID($countryID) {
return $this->_countryID = $countryID;
}
// set state id
public function setStateID($stateID) {
return $this->_stateID = $stateID;
}
public function getAllCountries() {
$this->db->select(array('c.id as country_id', 'c.slug', 'c.sortname', 'c.name as country_name'));
$this->db->from('countries as c');
$query = $this->db->get();
return $query->result_array();
}
// get state method
public function getStates() {
$this->db->select(array('s.id as state_id', 's.country_id', 's.name as state_name'));
$this->db->from('states as s');
$this->db->where('s.country_id', $this->_countryID);
$query = $this->db->get();
return $query->result_array();
}
// get city method
public function getCities() {
$this->db->select(array('i.id as city_id', 'i.name as city_name', 'i.state_id'));
$this->db->from('cities as i');
$this->db->where('i.state_id', $this->_stateID);
$query = $this->db->get();
return $query->result_array();
}
}
?>
Controller
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Location extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Site', 'location');
}
// get state names
public function index() {
$data['page'] = 'country-list';
$data['title'] = 'country List | TechArise';
$data['geCountries'] = $this->location->getAllCountries();
$this->load->view('location/index', $data);
}
// get state names
public function getstates() {
$json = array();
$this->location->setCountryID($this->input->post('countryID'));
$json = $this->location->getStates();
header('Content-Type: application/json');
echo json_encode($json);
}
// get city names
function getcities() {
$json = array();
$this->location->setStateID($this->input->post('stateID'));
$json = $this->location->getCities();
header('Content-Type: application/json');
echo json_encode($json);
}
}
?>
view
<?php
$this->load->view('templates/header');
?>
<div class="row">
<div class="col-lg-12">
<h2>Codeigniter Dependent country state city dropdown using jQuery Ajax with MySQL</h2>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<a href="#" class="pull-right btn btn-info btn-xs" style="margin: 2px;"><i class="fa fa-mail-reply"></i> Back To Tutorial</a>
</div>
</div>
<br>
<div class="row">
<div class="col-lg-12">
<span id="success-msg"></span>
</div>
</div>
<form class="dynamic-dependent-frm" id="dynamic-dependent-frm">
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<select title="Select Country" name="regcountry" class="form-control" id="country-name">
<option value="">Select Country</option>
<?php
foreach ($geCountries as $key => $element) {
echo '<option value="'.$element['country_id'].'">'.$element['country_name'].'</option>';
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<select title="Select State" name="state_name" class="form-control" id="state-name">
<option value="">Select State</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<select title="Select City" name="city_name" class="form-control" id="city-name">
<option value="">Select City</option>
</select>
</div>
</div>
</div>
</form>
<?php
$this->load->view('templates/footer');
?>
js
// get state
jQuery(document).on('change', 'select#country-name', function (e) {
e.preventDefault();
var countryID = jQuery(this).val();
getStatesList(countryID);
});
// get city
jQuery(document).on('change', 'select#state-name', function (e) {
e.preventDefault();
var stateID = jQuery(this).val();
getCityList(stateID);
});
// function get All States
function getStatesList(countryID) {
$.ajax({
url: baseurl + "location/getstates",
type: 'post',
data: {countryID: countryID},
dataType: 'json',
beforeSend: function () {
jQuery('select#state-name').find("option:eq(0)").html("Please wait..");
},
complete: function () {
// code
},
success: function (json) {
var options = '';
options +='<option value="">Select State</option>';
for (var i = 0; i < json.length; i++) {
options += '<option value="' + json[i].state_id + '">' + json[i].state_name + '</option>';
}
jQuery("select#state-name").html(options);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
// function get All Cities
function getCityList(stateID) {
$.ajax({
url: baseurl + "location/getcities",
type: 'post',
data: {stateID: stateID},
dataType: 'json',
beforeSend: function () {
jQuery('select#city-name').find("option:eq(0)").html("Please wait..");
},
complete: function () {
// code
},
success: function (json) {
var options = '';
options +='<option value="">Select City</option>';
for (var i = 0; i < json.length; i++) {
options += '<option value="' + json[i].city_id + '">' + json[i].city_name + '</option>';
}
jQuery("select#city-name").html(options);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}