Codeigniter Dependent country state city dropdown using jQuery Ajax with MySQL

In this tutorial, I am going to explain the dynamic dependent country state and city dropdown using jQuery Ajax in Codeigniter and MySQL. Dynamic dependent select box is used to implement country state city dropdown functionality. Using jQuery Ajax in Codeigniter and MySQL , you can easily implement dynamic dependent dropdown without page refresh. We will cover this tutorial in easy steps with live demo to develop complete dynamic dependent dropdown. We will also provide to download source code of live demo.

Step 1: Create MySQL Database and Tables

//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;

?>


Step 2: Create a model file
Create a model file named "Site.php" inside "application/models" folder.

/*
* 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.
*/

/**
* @package Razorpay : CodeIgniter Site
*
* @author TechArise Team
*
* @email info@techarise.com
*
* Description of Site Controller
*/

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();
}

}
?>


Step 3: Create a controller file
Next create a controller file named "Location.php" inside "application/controllers" folder.


/*
* 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.
*/

/**
* Description of Location Controller FrontEnd
*
* @author Jaeeme
*/
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);
}

}
?>

Step 4: Change Route file
So open "application/config/routes.php" file and add code like as bellow:

// create routes
$route['default_controller'] = 'location/index';
?>

Step 5: Create a view< file/strong>
Create a view file named "index.php" inside "application/views/emp" folder


$this->load->view('templates/header');
?>


Codeigniter Dependent country state city dropdown using jQuery Ajax with MySQL



































$this->load->view('templates/footer');
?>


Step 5: Create a file
Create a view file named “custom.js inside “assets/js” folder



// 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 +='';
for (var i = 0; i < json.length; i++) {
options += '';
}
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 +='';
for (var i = 0; i < json.length; i++) {
options += '';
}
jQuery("select#city-name").html(options);

},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}

Demo  [sociallocker] Download[/sociallocker]

Komentar

Postingan Populer