I have a select field. I must fill with options taken from a mysql table.
Here is some little php code I have done using codeigniter framework
$idcateg =
you could also just use $().load() and have your PHP code generate the <option>
tags
$return = "";
while ($row = mysql_fetch_array($res)) {
$value = $row['value'];
$text = $row{'text'];
$return .= "<option value='$value'>$text</option>\n";
}
print $return;
}
...
$('#select').load("<?=base_url()?>index.php/rubro/list_ajax/");
Try the following Code.
In Controller ---------
public function AjaxTest() {
$rollNumber = $this->input->post('rollNumber');
$query = "";
if($rollNumber !="")
{
$query = $this->welcome_model->get_students();
}
else
{
$query = $this->welcome_model->get_students_informationByRoll($rollNumber);
}
$array = array($query);
header('Content-Type: application/json', true);
echo json_encode($array);
}
In View Add a Select Option
<input type="text" id="txtSearchRoll" name="roll" value="" />
<input type="button" name="btnSubmit" value="Search Students" onclick="return CheckAjaxCall();"/>
<select id="myStudents">
<option>
--Select--
</option>
</select>
Now Scripts ----
function CheckAjaxCall()
{
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>welcome/AjaxTest',
dataType:'json',
data:{rollNumber: $('#txtSearchRoll').val()},
cache:false,
success:function(aData){
$('#myStudents').get(0).options.length = 0;
$('#myStudents').get(0).options[0] = new Option("--Select--", "0");
$.each(aData, function(i,item) {
$('#myStudents').get(0).options[$('#myStudents').get(0).options.length] = new Option(item[i].Name, item[i].roll);
// Display Value
});
},
error:function(){alert("Connection Is Not Available");}
});
return false;
}
Enjoy the code....
It's not much different.
$idcateg = trim($this->input->post('idcategory'));
$result = array();
$id = mysql_real_escape_string($idcateg);
$res = mysql_query("SELECT * FROM subcategories WHERE category = $id");
while ($row = mysql_fetch_array($res)) {
$result[] = array(
'id' => $row['subcatid'],
'desc' => $row['description'],
);
}
echo json_encode($result);
with:
$.post("<?=base_url()?>index.php/rubro/list_ajax/", {
'idcategory' : idc },
function(data) {
var sel = $("#select");
sel.empty();
for (var i=0; i<data.length; i++) {
sel.append('<option value="' + data[i].id + '">' + data[i].desc + '</option>');
}
}, "json");
Yes. You want to pass back a JSON-encoded array of objects containing name/value pairs. Then you can create your select iteratively using these.
$.post("<?=base_url()?>index.php/rubro/list_ajax/",
{'idcategory' : idc },
function(data){
var select = $('#selectName').empty();
$.each(data.values, function(i,item) {
select.append( '<option value="'
+ item.id
+ '">'
+ item.name
+ '</option>' );
});
}, "json");