如何使用ajax填充选择选项?

时间:2017-02-25 03:42:20

标签: javascript php jquery html ajax

当我点击“详细信息”按钮时,我想使用ajax填充我的选择选项。 该选项来自数据库,我尝试过:

选择选项:

<select id="update_listboxstock" size="5" class="form-control">

</select>

按钮代码:

<td style="text-align:center;">
       <button onclick="GetMenuDetails('.$row['kode_menu'].')" class="btn btn-warning" data-toggle="modal" data-target="#update_record_modal">Perbarui/Detail</button>
    </td>

Javascript:

function GetMenuDetails(id) {
        $.get("function_and_ajax/ajax.php",{
            ajx:"GetRecipe",
            kode_menu:id
        },function(result){
            $("update_listboxstock").html(result);
        });
    }

AJAX:

  include("function_connection.php");

    if(isset($_GET['ajx'])){
        if($_GET['ajx'] == 'GetRecipe'){
            $kode_menu = $_GET['kode_menu'];
            GetRecipe($kode_menu);
        }
    }

函数GetRecipe:

function GetRecipe($kode_menu){
            $conn = getConnection();
            echo "<option>".$_SESSION["kode_menu"]."</option>";
            $query = "SELECT DISTINCT S.NAMA_BARANG AS NAMA_BARANG, MD.JUMLAH AS JUMLAH, S.SATUAN AS SATUAN, S.KODE_STOK AS KODE_STOK FROM STOCKS S, MENUDETAILS MD, MENUS M WHERE S.KODE_STOK = MD.KODE_STOK AND MD.KODE_MENU = '".$_SESSION["kode_menu"]."'";
            $conn=getConnection();
            $result = $conn->query($query);
            if ($result->num_rows > 0){
                while($row = $result->fetch_assoc()){
                    echo "<option value=".$row['kode_stok'].">
                        ".$row['NAMA_BARANG'].
                        " - ".
                        $row['JUMLAH']." ".$row['SATUAN']."
                    </option>";
                }
            }
     }

抱歉我的英语不好......

2 个答案:

答案 0 :(得分:1)

GetMenuDetails js函数中有错误:

        $("#update_listboxstock").html(result);

而不是:

        $("update_listboxstock").html(result);

由于update_listboxstock是此选择的ID。

答案 1 :(得分:0)

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
 function GetMenuDetails(id) {
    $.get("function_and_ajax/ajax.php",{
        ajx:"GetRecipe",
        kode_menu:id
    },function(result){
       $.each(result, function(val, text) {
        $('#update_listboxstock').append( $('<option></option>').val(val).html(text) )
        });
       });

    });
}



</script>
</head>
<body>

<select id="update_listboxstock" size="5" class="form-control">

</select>
</body>
</html>