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 = trim($this->input->post('idcategory'));
$array1 = array(
'result' => $idcateg
);
echo json_encode($array1);
Now, the jQuery call...
$.post("<?=base_url()?>index.php/rubro/list_ajax/", {
'idcategory' : idc },
function(data){
alert(data.result);
}, "json");
The code works fine. When I call the post, I get the categoryid as a result.
Now, I should modify the code above, so I can do:
The array should be built with each element having a sub-array with id and name, right? Thanks a lot in advance for any help
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With