Hi,   I would like to give shot about how to populate data from Database in. In here I used Codeigniter  as PHP Framework, MySQL as DB and Jquery as JS Framework. I have 1 table (t_unit) with 2 fields (id_unit, unit_name). some how in another form I would like to capture id_unit into another table, then I should populate them into another form, so here are the details This is...

Populate select box data with Codeigniter, Ajax, Mysql

Hi,

 

I would like to give shot about how to populate data from Database in. In here I used Codeigniter  as PHP Framework, MySQL as DB and Jquery as JS Framework.

I have 1 table (t_unit) with 2 fields (id_unit, unit_name). some how in another form I would like to capture id_unit into another table, then I should populate them into another form, so here are the details

This is my Model

function fetch_unit() {

$this->db->select('id_unit, unit_name');
$records=$this->db->get('t_unit');
$data=array();

//$data[0] = 'SELECT'; 
foreach ($records->result() as $row)
{
$data[$row->id_unit] = $row->unit_name;
}
return ($data);
}

from above code, I will set id_unit as value and unit_name as display value.if we use Codeigniter as our framework then we should able to display dataset in view with very easy step.

here are my controller

$data['unit'] = $this->cdd_model->fetch_unit();
$data['title'] = 'Create CDD';
$this->load->view('home/index', $data);

then in your view you just use form_dropdown class to populate it

<div class="control-group">
<label class="control-label" for="cmpgn_unit" >Business Unit</label>
<div class="controls"> <?php echo form_dropdown('cmpgn_unit', $unit, 1,'id="cmpgn_bis_unit"'); ?>
</div> 
</div>

and thats it. you got data from DB into your select box.

we also able to populate it via jQuery like below (use same model like above, just modify lil bit your controller):

function fetch_unit() {
$unit = $this->cdd_model->fetch_unit(); 
echo json_encode($unit);
}

we use json to send parameter into view file. then from view file write down code like this:

<div class="control-group">
<label class="control-label" for="cmpgn_bis_unit" >Business Unit</label>
<div class="controls"> 
<select id="sUnit" name="cmpgn_unit"><option value="">Please Select</option></select>
</div> 
</div>

to call data via ajax, then we write js like below:

//Unit Select Box
$.post("<?php base_url(); ?>co/ctrl_cdd/fetch_unit", function(data) {
var sel = $("#sUnit");
sel.empty();
$.each(data, function(i, item){
$("#sUnit").append('<option value="' + i + '">'+ item + '</option>');
})
},"json");

 its Done!!!, pls take a look the id '#sUnit, as this id will get data from DB via ajax. Enjoy the code.

Rgds,

Afif


About Author

Husnul Afif


Comment & Discussions

  • prakasa (Guest)
    keren banget sih kamu pake b Ing... uhh gemes deh :*

  • Derry Alif
    function(i, item)
    hmm mas bro i sama item ini maksudnya gimana ya
    jelasin dikit mas

  • Please LOGIN before if you want to give the comment.