Unable to create the third drop down using ajax in codeigniter - ajax

I am trying to create ajax dropdown in three layers state, city and location in codeigniter 2.1.4. The first layer is working fine I am able to fetch the city list from state id but unable to fetch location from city id. I thing I am doing some mistake in the ajax I need help. My code is mentioned below:
view
<div id="innerdiv1">
<label>State</label>
<br />
<select name="state_id" id="state_id">
<option value="">-- Select State --</option>
<?php foreach ($states as $all_states): ?>
<option value="<?=$all_states['id'];?>"><?=$all_states['state'];?></option>
<?php endforeach ?>
</select>
</div>
<div id="innerdiv2">
<label>City</label>
<br />
<div id="city">
<select name="city_id" id="city_id">
<option value="">-- Select City-- </option>
</select>
</div>
</div>
<div id="innerdiv1">
<label>Location</label>
<br />
<div id="location">
<select name="location_id" id="location_id">
<option value="">-- Select Location-- </option>
</select>
</div>
</div>
Ajax
$(document).ready(function () {
$('#state_id').change(function () {
var selState = $(this).val();
console.log(selState);
$.ajax({
url: "pages/get_cities",
async: false,
type: "POST",
data: "state="+selState,
dataType: "html",
success: function(data) {
$('#city').html(data);
}
})
});
$('#city_id').change(function () {
var selCity = $(this).val();
alert(selCity);
console.log(selCity);
$.ajax({
url: "pages/get_locations",
async: false,
type: "POST",
data: "cities="+selCity,
dataType: "html",
success: function(data) {
$('#location').html(data);
}
})
});
});
</script>
city model
<?php
class City_model extends CI_Model {
public function __construct() {
$this -> load -> database();
//$this->output->enable_profiler(TRUE);
}
function get_cities($state){
if($state != NULL){
$this->db->where('state_id', $state);
$query = $this->db->get('city');
$cities = array();
$html = '';
if($query->result())
{
$html .= '<select id="city_id" name="city_id">';
$html .= '<option value="">-- Select City --</option>';
foreach ($query->result() as $city)
{
//$cities[$city->id] = $city->city;
$html .= '<option value="'.$city->id .'">'.$city->city.'</option>';
}
$html .= '</select>';
return $html;
}
else
{
return FALSE;
}
}
else
{
$html = '<option value="">--Select City--</option>';
return $html;
}
}
}
Controller
class Pages extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('home_model');
$this->load->model('sub_cat_model');
$this->load->model('state_model');
$this->load->model('city_model');
$this->load->model('location_model');
$this->load->library('email');
}
public function index()
{
$data['state'] = $this->home_model->get_state();
$data['title'] = 'Rimi Classified - Home';
$this->load->view('templates/header', $data);
$this->load->view('index', $data);
$this->load->view('templates/footer', $data);
}
public function sign_up()
{
$data['states'] = $this->state_model->get_states();
$data['error'] = '';
$data['title'] = 'Rimi Classified - Sign up';
$this->load->view('templates/header1', $data);
$this->load->view('sign-up', $data);
$this->load->view('templates/footer', $data);
}
public function get_cities()
{
$state_id = $this->input->post('state');
echo $this->city_model->get_cities($state_id);
}
public function get_locations()
{
$city_id = $this->input->post('cities');
echo $this->location_model->get_locations($city_id);
}
}

Replace
$('#city_id').live("change", function () {
with below code
$(document).on("change", "#city_id", function(){

try to add an alert statement in your first ajax call's success function. also add an error function to know that the first AJAX call is completing successfully.
Use the documentation from here to check if you've correctly implemented the AJAX model.
Jquery-Ajax

Related

codeigniter dependent dropdown error

This is my code. It does not work with codeigniter 3.0 and jquery. I need to use dropdown dependent so I made that but it will be display "Error occur..." by alert() after choosing any item in first dropdown.
Please have a look to my source code. I don't know what is wrong. Thanks everyone
VIEW:
<script type="text/javascript">
$(document).ready(function(){
$('#senf').on('change', function(){
var senf_id = $(this).val();
if(senf_id == '')
{
$('#raste').prop('disabled', true);
}
else
{
$('#raste').prop('disabled', false);
$.ajax({
url:"<?php echo base_url() ?>index.php/shoppings/get_subgroup/",
type: "POST",
data: {'senf_id' : senf_id},
dataType: 'json',
success: function(data){
alert('okkk');
},
error: function(){
alert('Error occur...!!');
}
});
}
});
});
</script>
<div class="form-group ">
<label for="group_name" class="control-label col-lg-2">group 1</label>
<select id="senf" name="group">
<option value="" selected="selected">select</option>
<?php
foreach ($get_groups as $value) {
$group_id = $value['group_shop_id'];
$group_name = $value['group_shop_name'];
?>
<option value="<?php echo $group_id; ?>"> <?php echo $group_name; ?> </option>
<?php } ?>
</select>
<label for="raste" >group 2</label>
<select id="raste" name="raste">
<option value="">select</option>
</select>
</div>
CONTROLLER:
public function get_subgroup(){
$id = $this->input->post('senf_id');
$ajax_get_subgroup = $this->shopping_model->ajax_get_subgroup($id);
$pro_select_box = '';
$pro_select_box .= '<option value="">Select Province</option>';
foreach($ajax_get_subgroup as $ajax_get_subgroup_value){
$pro_select_box .= '<option>'. $ajax_get_subgroup_value->cat_shop_name .'</option>';
}
echo json_encode($pro_select_box);
}
MODEL:
public function ajax_get_subgroup($id){
$query = $this->db->get_where('cat_shopping_group', array('group_shop_id' => $id));
return $query->result();
}
try this
Controller
public function ajax_get_subgroup()
{
extract($_POST);
$tmp='';
$sql = "SELECT * FROM cat_shopping_group where group_shop_id=$id";
$data = $this->db->query($sql)->result_array();
$tmp .="<option value=''>-- Select --</option>";
foreach($data as $row)
{
$tmp .="<option value='".$row['your_id']."'>".$row['cat_shop_name ']."</option>";
}
die($tmp);
}`
AJAX
function get_data()
{
var id = $('#senf').val()
datana= 'id='+id
$.ajax({
type: 'POST',
url: '<?=base_url()?>your_controller/ajax_get_subgroup',
data: datana,
error: function(data) {
alert('Failed');
},
success: function(data)
{
$('#raste').html(data)
}
})
}
Views
<select id="senf" name="group" onchange='ajax_get_subgroup();'>
<option value="" selected="selected">select</option>
<?php
your code
?>
</select>
<select id="raste">
</select>
Hope this help.

Array to string conversion on creating chained combobox with codeigniter

i'm trying to create a chained combobox (2 combobox) with codeigniter, the result is ok but when i inspect it with dev tools on chrome show:
array to string conversion
and i don't know how to solve it.
Here's my code:
Controller:
public function create()
{
$this->data['get_all_data'] = $this->Category_model->getkat();
$this->load->view('back/tool/tool_add', $this->data);
}
function get_subkat()
{
$id_kat = $this->input->post('id_kat');
$datasubkat = $this->Category_model->getdatasubkat($id_kat);
$this->data .= "<option value=''>-- CHOOSE --</option>";
foreach($datasubkat as $data_subkat)
{
$this->data .= "<option value='$data_subkat[id_subkat]'>$data_subkat[nama_subkat]</option>";
}
echo $this->data;
}
Model:
function getkat()
{
$result = $this->db->get($this->table);
if($result->num_rows() > 0)
{
return $result->result_array();
}
else
{return array();}
}
function getdatasubkat($id_kat)
{
$this->db->where('id_kat', $id_kat);
$result = $this->db->get('subkategori');
if($result->num_rows() > 0)
{
return $result->result_array();
}
else
{return array();}
}
View:
<script type="text/javascript">
$(document).ready(function(){
$("#kat").change(function(){
var id_kat = $("#kat").val();
$.ajax({
type: 'POST',
url: "<?php echo base_url('admin/tool/get_subkat'); ?>",
data:"id_kat="+id_kat,
success: function(data) {
$("#subkat").html(data);
}
});
});
});
</script>
<div class="row">
<div class="col-xs-6"><b>Category</b>
<select name="kat" id="kat" class="form-control">
<option value="">-- CHOOSE --</option>
<?php
foreach($get_all_data as $category){
echo "<option value=".$category['id_kat'].">".$category['nama_kat']."</option>";
}
?>
</select>
</div>
<div class="col-xs-6"><b>Sub category</b>
<select name="subkat" id="subkat" class="form-control">
<option value="">-- CHOOSE --</option>
</select>
</div>
</div>
Any help will be so appreciated, thank you

Change input value using ajax in codeigniter

I wanted to change an input value based on the selection from a combobox in codeigniter. I tried to code it but theres nothing to be displayed.
Here is my code in my controller.....
function fill_info()
{
// retrieve the group and add to the data array
$group_id = $this->input->post('group_id');
$data = "0.00";
if($group_id)
{
$this->load-model('Base_amount_setting_model');
$baseamount = $this->Base_amount_setting_model->getbaseamount($group_id);
$data .= $baseamount;
echo $data;
}
else
{
echo $data;
}
}
And in my Base_amount_setting_model there is this method....
function getbaseamount($group_id)
{
$this->db->where('group_id',$group_id);
$baseamount = $this->db->get('base_amount_setting')->row()->amount;
if($baseamount -> num_rows() == 1)
{
return $baseamount->result();
}
}
And there in my view the ajax looks like this.....
<script>
$(document).ready(function()
{
$("#group_id").change(function()
{
var group_id = $("#group_id").val();
$.ajax({
type : "POST",
url : "<?php echo base_url('payment/fill_info'); ?>",
data : "group_id=" + group_id,
success: function(data)
{
$("#base_amount").html(data);
}
});
});
});
</script>
and finally my form is like this...
<div class="control-group">
<label class="control-label" for="select01">Group Id </label>
<div class="controls">
<select class="chzn-select" name="group_id" id="group_id" placeholder="Group Id" value="<?php echo $group_id; ?>">
<option></option>
<?php
if (count($groups)) {
foreach ($groups as $list) {
echo "<option value='". $list['group_id'] . "'>" . $list['group_name'] . "</option>";
}
}
?>
</select>
<label for="int" class="err"><?php echo form_error('group_id') ?></label>
</div>
<input class="input-xlarge disabled" id="base_amount" name="base_amount" type="text" placeholder="Base Amount" disabled="">
<input class="input-xlarge disabled" id="total_members" type="text" placeholder="Total Members" disabled="">
</div>
Thank You!
change this $("#base_amount").html(data);
to $("#base_amount").val(data);
Actually if you get your value after ajax hit in data object
then only change this :
$("#base_amount").html(data);
to
$("#base_amount").val(data);
Actually .html replce the html not change the value.
i'm really curious - but i think your model doesnt return anything
try the following
function getbaseamount($group_id)
{
$query = $this->db
->where('group_id',$group_id)
->get('base_amount_setting');
if ($query->num_rows() == 1)
{
$obj = $query->row();
return $obj->amount;
}
}
and as others suggested
change your script code to
$("#base_amount").val(data);
and your controller function should look like
function fill_info()
{
// retrieve the group and add to the data array
$group_id = $this->input->post('group_id');
$data = "0.00";
if($group_id)
{
$this->load-model('Base_amount_setting_model');
$baseamount = $this->Base_amount_setting_model->getbaseamount($group_id);
echo $baseamount;
}
else
{
echo $data;
}
}

dynamic codeigniter select not working

controller
car.php
<?php
class Car extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('company_model');
}
public function index()
{
//starts by running the query for the countries
//dropdown
$data['companydrop'] = $this->company_model->company();
//loads up the view with the query results
$this->load->view('car_view', $data);
}
//call to fill the second dropdown with the cities
public function car_model()
{
//set selected country id from POST
echo $company_id = $this->input->post('company_id',TRUE);
//run the query for the cities we specified earlier
$cardata['cardrop']=$this->company_model->car($company_id);
print_r($cardata);
$output = null;
foreach ($cardata['cardrop'] as $row)
{
//here we build a dropdown item line for each
// query result
$output .= "<option value='".$row->car_model."'>".$row->car_model."</option>";
}
echo $output;
}
}
?>
model
company_model
<?php
class Company_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
//fill your contry dropdown
public function company()
{
$this->db->select('company_id,company_name');
$this->db->from('company');
$query = $this->db->get();
// the query mean select cat_id,category from
//category
foreach($query->result_array() as $row){
$data[$row['company_id']]=$row['company_name'];
}
// the fetching data from database is return
return $data;
}
//fill your cities dropdown depending on the selected city
public function car($company_id=string)
{
$this->db->select('car_id,car_model');
$this->db->from('car');
$this->db->where('company',$company_id);
$query = $this->db->get();
return $query->result();
}
}
?>
view
car_view
<html>
<head>
<title>car dealers</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#companydrop").change(function(){
/*dropdown post *///
$.ajax({
url:"<?php echo base_url();?>index.php/car/car_model",
data: {id:$(this).val()},
type: "POST",
success:function(data){
$("#cardrop").html(data);
alert(data);
}
});
});
});
</script>
<style>
body{
no-repeat;
background:url(../../../video-fallback-background.jpg)
}
</style>
</head>
<body>
<!--company dropdown-->
<?php echo form_dropdown('companydrop',$companydrop,'','class="required" id="companydrop"'); ?>
<br />
<br />
<!--car dropdown-->
<select name="cardrop" id="cardrop">
<option value="">Select</option>
</select>
<br />
</body>
</html>
dynamic dropdown is not working as the first select which is the
company name is working as it is fetched from database,but car model is not working,it not fetched to the dropdown.i need to fetch the car company model from database and then after selecting the company the model of that specified company has to be listed in the second dropdown.i have created database in phpmyadmin and created two table car and company,in company copany_id and company_name where as in car has car_id,car_name and company_id
Check this sample code for creating dropdown in codeigniter.
<?php
$js = 'id="unicode" class="form-control"';
$unicode = array(
'2' => 'No',
'1' => 'Yes'
);
echo form_dropdown('unicode', $unicode, set_value('unicode'), $js);
?>
Here Dropdown id is unicode,class is form-control.
Html will look like :
<select name="unicode" id="unicode" class="form-control">
<option value="2">No</option>
<option value="1">Yes</option>
</select>
You can get you values from db in an array and then store it in a variable like $unicode.Hope this helps.Check this ref link
For setting another dropdown based on first dropdown:
$("#dropdown1").change(function () {
var end = this.value;
$('#dropdown2').val(end );
});
In Your Car Controller Please remove print_r($cardata); first.
Then see in your console what response you are getting from the call. I suggest you to get data in json format and parse it on client end. It is the best practice.
i corrected the code and finally it worked,i will post the correct code, if it helps anyone in future.thanks to everyone who tried to help me..
controller
car.php
<?php
class Car extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('company_model');
}
public function index()
{
$data['companydrop'] = $this->company_model->company();
$this->load->view('car_view', $data);
}
public function car_model()
{
$company_id = $this->input->post('company_id',TRUE);
$cardata['cardrop']=$this->company_model->car($company_id);
$output = null;
foreach ($cardata['cardrop'] as $row)
{
$output .= "<option value='".$row->car_model."'>".$row->car_model."</option>";
}
echo $output;
}
}
?>
model
company_model
<?php
class Company_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function company()
{
$this->db->select('company_id,company_name');
$this->db->from('company');
$query = $this->db->get();
foreach($query->result_array() as $row){
$data[$row['company_id']]=$row['company_name'];
}
return $data;
}
public function car($company_id)
{
$this->db->select('car_id,car_model');
$this->db->from('car');
$this->db->where('company_id',$company_id);
$query = $this->db->get();
return $query->result();
}
}
?>
view
car_view
<html>
<head>
<title>car dealers</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#companydrop").change(function(){
/*dropdown post *///
$.ajax({
url:"<?php echo base_url();?>index.php/car/car_model",
data: {company_id:$(this).val()},
type: "POST",
success:function(data){
$('#cardrop option[value!=0]').remove()
$("#cardrop").append(data);
}
});
});
});
</script>
<style>
body{
no-repeat;
background:url(../../../video-fallback-background.jpg)
}
</style>
</head>
<body>
<center><font color="#333366"><strong></strong><h2>CR Motors</h2></font></center>
<center><font color="#FF8000"><h3>Select the car to purchase...</h3></center></font>
<!--company dropdown-->
<tr>
<td>
<font color="#00FF99">
Select the company</font>
<?php echo form_dropdown('companydrop',$companydrop,'','class="required" id="companydrop"'); ?> </td>
</tr>
<br />
<br />
<!--car dropdown-->
<tr>
<td>
<font color="#00FF99">
Select the model</font>
<select name="cardrop" id="cardrop">
<option value="0">Select</option>
</select>
</td>
</tr>
<br />
</body>
</html>

Making Dependent Combobox in codeigniter project

i am suffering greatly but still unable to make a dependent dropdown box in Codeigniter .
Here is the schema :
groups(group_id,group)
forum(forum_id,subject)
group_forum(group_id,forum_id)
Here is my code :
model
function get_group(){
$query = $this->db->get('group');
return $query->result();
}
function get_subject_by_group($id)
{
$subjects=array();
$this->db->from('forum');
$this->db->join('group_forum','group_forum.forum_id=forum.forum_id','group_id='.$id);
$q=$this->db->get();
foreach($q->result() as $y)
{
$subjects[$y['forum_id']] = $y['subject'];
}
return $subjects;
}
}
Controller:
<?php
class C_control_form extends CI_Controller {
function add_all(){
#Validate entry form information
$this->load->model('Model_form');
$this->form_validation->set_rules('f_group', 'Group', 'trim|required');
$this->form_validation->set_rules('f_forum', 'Forum', 'trim|required');
$data['groups'] = $this->Model_form->get_group(); //gets the available groups for the dropdown
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header_for_combo',$data);
$this->load->view('view_form_all', $data);
$this->load->view('footer_for_combo',$data);
}
else
{
#Add Member to Database
$this->Model_form->add_all();
$this->load->view('view_form_success');
}
}
function get_subjects($group)
{
//echo "hi";
$this->load->model('Model_form');
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->Model_form->get_subject_by_group($group)));
}
}
?>
View
<html>
<head>
<script type="text/javascript" src="<?php echo base_url("js/jquery-1.7.2.min.js"); ?>" ></script>
<script type="text/javascript">
// $('#f_group, #f_forum').hide();
$(document).ready(function(){
$('#f_group').change(function(){
var group_id = $('#f_group').val();
if (group_id != ""){
var post_url = "index.php/c_control_form/get_subjects/"+group_id;
// var post_url = "<?php echo base_url();?>"+"c_control_form/get_subjects"+group_id;
$.ajax({
type: 'POST',
url: post_url,
dataType : 'json',
success: function(subjects) //we're calling the response json array 'cities'
{
$("#f_forum > option").remove();
// $('#f_forum').empty();
// $('#f_forum, #f_forum_label').show();
$.each(subjects,function(forum_id,subject)
{
var opt = $('<option/>'); // here we're creating a new select option for each group
opt.val(forum_id);
//alert(id);
opt.text(subject);
$('#f_forum').append(opt);
});
} //end success
}); //end AJAX
} else {
$('#f_forum').empty();
// $('#f_forum, #f_forum_label').hide();
}//end if
}); //end change
});
</script>
</head>
<body>
<?php echo form_open('c_control_form/add_all'); ?>
<p>
<label for="f_group">Group<span class="red">*</span></label>
<select id="f_group" name="f_group">
<option value=""></option>
<?php
foreach($groups as $group){
echo '<option value="' . $group->group_id . '">' . $group->group_name.'</option>';
}
?>
</select>
</p>
<p>
<label for="f_forum">Subject<span class="red">*</span></label>
<select id="f_forum" name="f_forum" id="f_forum_label">
<option value=""></option>
</select>
</p>
<?php echo form_close(); ?>
</body>
Please change
$subjects[$y['forum_id']] = $y['subject'];
to
$subjects[$y->forum_id] = $y->subject;
in the model file. Also spaces or newlines in model php file after and before the php tags.
EDIT: Added below
function(subjects){
var select = $('#f_forum').empty();
$.each(subjects.values, function(i,item) {
select.append( '<option value="'
+ item.id
+ '">'
+ item.name
+ '</option>' );
});

Resources