views:

821

answers:

3

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

+2  A: 

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");
cletus
hi cletus. Worked perfect. Can you tell me now what if nothing is returned? (i.e. mysql returns empty).. how can i tell if result is empty?thanks
Enrique
A: 

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");
tvanfosson
A: 

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/");
Scott Evernden
Awesome tip/idea... Will try it!! Thanks Scott !!
Enrique