AJAX填充下拉列表中的未定义值

时间:2019-05-07 07:49:47

标签: php sql-server ajax

第二个下拉列表应基于第一个下拉列表中的选择进行填充,但是我在第二个下拉列表中获得的值为“ undefined”。从SQL Server提取数据。在Google开发工具中查看时,我可以看到,当我单击第一个下拉菜单中的某些项时,ajaxfile.php会正确执行查询。

INDEX.PHP

    <!doctype html>
  <?PHP
$server = "server";
$options = array(  "UID" => "user",  "PWD" => "pass",  "Database" => 
"database");
$conn2 = sqlsrv_connect($server, $options);
if ($conn2 === false) die("<pre>".print_r(sqlsrv_errors(), true));
echo " ";
?>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
            <section id="formaT2" class="formaT2 formContent">
            <div class="row">
                <div class="col-md-2 col-3 row-color remove-mob"></div>
                <div class="col-md-5 col-9 bg-img" style="padding-left: 0; 
padding-right: 0;">
                    <h1>Form</h1>
                    <div class="rest-text">
                       <div class="contactFrm">
                          <p class="statusMsg <?php echo 
!empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>

                            <form action="connection.php" method="post">
                                <div>machinery</div>     
<select id="machinery">
<option value="0">--Please Select Machinery--</option>

<?php       
// Fetch Department
$sql = "SELECT Machinery FROM T013";
$machanery_data = sqlsrv_query($conn2,$sql);
while($row = sqlsrv_fetch_array($machanery_data) ){
  $machinery = $row['Machinery'];

  // Option
  echo "<option value='".$machinery."' >".$machinery."</option>";
 }
 ?>
</div>


</select>
    <div class="clear"></div>
                <div>Sub Machinery</div>
                <select id="sub_machinery">
       <option value="0">- Select -</option>
    </select>

                                <input type="submit" name="submit" 
id="submit" class="strelka-send" value="Insert">
                                <div class="clear"> </div>
                            </form>
                        </div> 
                    </div>
                </div>
            </div> 
        </section>
        </script>
      <script type="text/javascript">
      $(document).ready(function(){

    $("#machinery").change(function(){
        var machinery_id = $(this).val();

        $.ajax({
            url:'ajaxfile.php',
            type: 'post',
            data: {machinery:machinery_id},
            dataType: 'json',
            success:function(response){

                var len = response.length;

                $("#sub_machinery").empty();
                for( var i = 0; i<len; i++){
                    var machinery_id = response[i]['machinery_id'];
                    var machinery = response[i]['machinery'];

                    $("#sub_machinery").append("<option 
value='"+machinery_id+"'>"+machinery+"</option>");

                }
            }
        });
    });

});
      </script>
</body>
</html>

AJAXFILE.PHP

<?php
    $server = "server";
    $options = array(  "UID" => "user",  "PWD" => "pass",  
    "Database" => "database");
    $conn2 = sqlsrv_connect($server, $options);
    if ($conn2 === false) die("<pre>".print_r(sqlsrv_errors(), true));
    echo " ";

        $machineryID = $_POST['machinery'];   // department id
$sql = "SELECT MachineID FROM T013 WHERE Machinery='$machineryID'";
$result = sqlsrv_query($conn2,$sql);

$machinery_arr = array();

while( $row = sqlsrv_fetch_array($result) ){
    $machinery = $row['MachineID'];

    $machinery_arr[] = array("MachineID" => $machinery);
}

// encoding array to json format
echo json_encode($machinery_arr);
?>

1 个答案:

答案 0 :(得分:1)

我认为,该问题是由所使用的命名约定引起的。在ajaxfile中的PHP代码中,输出数组为每个结果添加了一个新数组-此键的名称为MachineID,但在ajax回调函数中,您尝试分配machinery_id和{ {1}}到新生成的选项元素。

我的建议是简化名称-使它们与众不同并易于识别它们的名称。我这样重写了上面的内容-尽管它当然未经测试:

通常,我建议您使用machinery,因为上述内容可能容易受到SQL注入的攻击,但是我不知道SQL Server和PHP对准备好的语句有什么支持。如果可用,请使用它们!

prepared statements

ajaxfile.php

<script>
    $(document).ready(function(){
        $("#machinery").change(function(){
            $.ajax({
                url:'ajaxfile.php',
                type:'post',
                data:{ machinery:$(this).val()},
                dataType:'json',
                success:function(response){
                    $("#sub_machinery").empty();

                    for( let n in response ){
                        let obj=response[n];
                        $("#sub_machinery").append( new Option( obj.id, obj.id ) );
                    }
                }
            });
        });

    });
</script>