We Guarantee the Best and Free technical solutions
Some Usefull link in this Application will redirect your mind to a new techical world
Populating a dropdown using another dropdown using Codeigniter with jquery/Ajax.
Complete scripts and demo are given below.
Step1:Open the database.php inside the config folder and make changes like as below
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'testlogin';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
step2:create a table inside testlogin database and insert the values please see the query below.
CREATE TABLE IF NOT EXISTS `country_state` (
`country` varchar(250) NOT NULL,
`state` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `country_state`
--
INSERT INTO `country_state` (`country`, `state`) VALUES
('india', 'kerala'),
('india', 'karnataka'),
('USA', 'Texas'),
('USA', 'Newyork'),
('UAE', 'Abhudhabi'),
('UAE', 'Dubai');
step3:Create a model file inside application/model/countrystate.php
class Countrystate extends CI_Model {
function loadcountries() {
$query = $this->db->query("SELECT DISTINCT country FROM country_state");
if ($query->num_rows > 0) {
return $query->result();
}
}
function loadstatesfromcountries($country) {
$query = $this->db->query("SELECT state FROM country_state WHERE country = '{$country}'");
if ($query->num_rows > 0) {
return $query->result();
}
}
}
step4: create controllers inside the controllers folder-application/controllers/countrystate_disp.php
class Countrystate_disp extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('countrystate','',TRUE);
}
function index() {
$arrCountries = $this->countrystate->loadcountries();
foreach ($arrCountries as $countries) {
$arrcountries[$countries->country] = $countries->country;
}
$data['country'] = $arrcountries;
$this->load->view('loadcountrystate',$data);
}
function ajax_call() {
if (isset($_POST) && isset($_POST['country'])) {
$country = $_POST['country'];
$arrStates = $this->countrystate->loadstatesfromcountries($country);
foreach ($arrStates as $states) {
$arrstates[$states->state] = $states->state;
}
print form_dropdown('state',$arrstates);
} else {
redirect('site');
}
}
}
Click to see the Demo