如何根据下拉菜单选择值预填表单?

时间:2015-02-05 10:09:53

标签: javascript php jquery html mysql

我的表单有一个下拉选择菜单,可以从我的数据库中加载发票ID。我尝试根据从下拉菜单中选择的发票金额预填表单。在我的数据库中有一列" invoiceidcopy"其中包含一个值,显示为我的下拉菜单的选择。如果你在我的数据库表的图像中注意到你会注意到第一行/记录的invoiceidcopy字段是空白的......在我的下拉菜单中......当然......第一个选择是空白的。最终我的代码下面我试图预先填写我的表单只有当我从下拉菜单中选择空白选项但不能选择其他2个选项时?如何根据下拉菜单选择值预填表单?

DataBase

FORM

<form action="#">

<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>

<button id="submit-id">Prefill Form</button>

<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">



<button id="submit-form" name="Submit-form" type="submit">Submit</button>


</form> 

SCRIPT

<script>
     $(function(){


        $('#submit-id').on('click', function(e){  


            var invoiceidcopy = $('#dropdown-select').val();
            e.preventDefault(); 

             $.ajax({
              url: "/tst/orders2.php",
              data: {
                invoiceidcopy: invoiceidcopy
              }
            }).done(function(data) {

    data = JSON.parse(data);

$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);


});
        });
     });
</script>

/tst/orders2.php

<?php

// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");


// Check if the connection failed
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  die();
}

   if (isset($_GET['invoiceidcopy']))
{
    $invoiceidcopy= $_GET['invoiceidcopy'];

   $query = "SELECT txt1, txt2, q1
        FROM seguin_orders
  WHERE invoiceidcopy = '".($invoiceidcopy)."'";

    $result = mysqli_query($con,$query);

    while ($row = mysqli_fetch_assoc($result)) 
        {
 echo json_encode($row);
 die(); 
    }
}
?>

1 个答案:

答案 0 :(得分:0)

似乎您的错误来源是您通过ajax发送到php的json数据。您应该尝试将数据键括在引号中,以便javascript不会将其替换为变量值。

   data: {
       'invoiceidcopy': invoiceidcopy
   }

另一个可能的错误来源是sql从表中选择记录。 您是否尝试过删除变量名称中的括号

 $query = "SELECT txt1, txt2, q1
        FROM seguin_orders
  WHERE invoiceidcopy = '".$invoiceidcopy."'";

甚至使用像

这样的大括号
 $query = "SELECT txt1, txt2, q1
        FROM seguin_orders
  WHERE invoiceidcopy = {$invoiceidcopy}";

最好在将值发送到php之前检查它,以确保它符合您的预期。例如,您可以执行以下操作:

 e.preventDefault();
    var invoiceidcopy = $('#dropdown-select').val();
    alert(invoiceidcopy); /*display the value to confirm it is correct */
    // use the javascript console
    console.log(invoiceidcopy);