jQuery populate items into a Select using jQuery ajax json, php

ajax, jquery, json, php, post

Solution

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");

Problem

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: - post the ajax call sending the category id. this is done - get subcategories for this category, and build the array * - json_encode the array and echo * - get results back in jQuery ajax call, decode and build the < select > field * 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

Original source