10

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

4 Answers 4

38

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");
Sign up to request clarification or add additional context in comments.

3 Comments

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
data.lenght will be 0
Or, instead of the for, could be: $.each(data, function(key, val) { sel.append($("<option>").val(data[key].id).text(data[key].desc)); });;
8

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

Comments

1

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

2 Comments

Awesome tip/idea... Will try it!! Thanks Scott !!
be aware that according to my experience this solution may not work on IE8 and below due to a bug in DOM manipulation using innerHTML (webbugtrack.blogspot.it/2007/08/…) - however it works well on other browsers, including IE 9+
1

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....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.