user7047368 user7047368 - 1 month ago 16
jQuery Question

Codeigniter ajax country state dropdown is not working

Hi I am having registration form which inlcudes countries and stated dropdown.Not able to get the states list after slecting countries.In Console getting response as page not found.Here is my code.

Controller:

function signup()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');

$this->form_validation->set_rules('country_id','Country Name','required');
$this->form_validation->set_rules('state_id','State Name','required');
$this->form_validation->set_rules('city_id','City Name','required');
if($this->form_validation->run()== FALSE)
{
$data['country'] = $this->signup_model->getcountry();
$data['mainpage']='signup';
$this->load->view('templates/template',$data);
}
else
{
$this -> signup_model -> insertprofiledetails();
$this->flash->success('<h2>Profile Details Added Successfully!</h2>');
redirect('welcome/add');
}
}

public function ajax_state_list($country_id)
{
$this->load->helper('url');
$this->load->model('signup_model');
$data['state'] = $this->signup_model->getstate($country_id);
$this->load->view('ajax_get_state',$data);
}


Model:

function getcountry()
{
$this -> db -> select('*');
$query = $this -> db -> get('countries');
return $query->result();
}

function getstate($country_id='')
{
$this -> db -> select('states.*');
$this -> db -> where('country_id', $country_id);
$query = $this -> db -> get('states');
return $query->result();
}


View:

<script>
function getstatedetails(id)
{
//alert('this id value :'+id);
$.ajax({
type: "POST",
url: '<?php echo base_url();?>welcome/ajax_state_list '+id,
data: id='cat_id',
success: function(data){
//alert(data);
$('#old_state').html(data);
},
});
}
</script>
<div class="form-group">
<label class="sr-only" for="form-address2">Country</label>
<select name="country_details" class="form-control countries" id="country_details" onChange="getstatedetails(this.value)">
<option value="" selected="selected" >Select Country</option>
<?php foreach($country as $count): ?>
<option value="<?php echo $count->country_id; ?>"><?php echo $count->country_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label class="sr-only" for="form-address2">State</label>
<select name="select_state" class="form-control countries" id="old_state" onChange="getcitydetails(this.value)">
<option selected="selected">Select State</option>
</select>
</div>


ajax_get_state:

<select name="select" onChange="getstatedetails(this.value)">
<option value="" selected="selected" >Select State</option>
<?php foreach($state as $stt): ?>
<option value="<?php echo $stt->state_id; ?>"><?php echo $stt->state_name; ?></option>
<?php endforeach; ?>
</select>

Answer

I thinks your forget use / after ajax_state_list

Edit your jqeury script :

url: '<?php echo base_url();?>welcome/ajax_state_list/'+id,