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

十年热恋 提交于 2019-12-17 22:57:31

问题


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


回答1:


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



回答2:


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



回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/1745704/jquery-populate-items-into-a-select-using-jquery-ajax-json-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!