Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 562
Enrique Avatar asked Nov 17 '09 00:11

Enrique


2 Answers

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");
like image 183
cletus Avatar answered Oct 20 '22 19:10

cletus


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");
like image 35
tvanfosson Avatar answered Oct 20 '22 18:10

tvanfosson