从php

时间:2018-03-15 17:20:03

标签: javascript php jquery html ajax

我有一个表单,我必须添加多个产品。通过单击按钮逐个添加这些产品。以下是相同的代码:

order.php

<script>
    $('#addOrderProduct').click(function(){
      var j = 1;
      var dataString = "j="+j;
      $.ajax({
        url: "addProdToOrder.php",
        type: "post",
        data: dataString,
        success: function(response){
          $('.dynamics').append(response);
        }
      });
    });
</script>

这是动态地向表中添加行的脚本。

addProdToOrder.php

<?php
<tr style="text-align: center;" id="products">
  <td><?php echo $j; ?></td>
  <td><select class="form-control" name="code" id="productID" style="width: 429px;">
    <?php

    $sql = "SELECT * FROM `product`";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
          echo "<option id='".$row['code']."' value='".$row['code']."'>".$row['pname']."</option>";
        }
    } else {
        echo "0 results";
    }
    ?>
    </select>
  </td>
  <td><input type="text" name="hsnNo" id="hsnNo" readonly></td>
  <td><input type="text" name="qty" id="qty" readonly></td>
  <td class="coljoin"><input type="number" format="2" name="amount"></td>
  <td>
    <span class="fa fa-trash"></span>
  </td>
</tr>
?>

现在,一旦添加了一行,我想根据select选项设置表单值。我已经实现了代码,但它只运行一行。我希望相同的代码以相同的形式运行多行。这是代码:

order.php

<script>
$('#productID').change(function(){
  var code = $(this).val();
  var dataString = 'code='+code;

  $.ajax({
    url: "getProdDets.php",
    type: "post",
    data: dataString,
    success: function(response){
      var Vals = JSON.parse(response);
      $("input[name='hsnNo']").val(Vals.hsnNo);
      $("input[name='qty']").val(Vals.qty);
    }
  });
});
</script>

表单应如下所示:Multiple Row addition on Add Product Button

ajax调用以设置表单字段的PHP页面是:

getProdDets.php

<?php
require('../config.php');
$code = isset($_POST['code']) ? $_POST['code'] : '';
if(!empty($_POST)){
$sql = "SELECT * FROM `product` WHERE `code`='$code'";
$result = $conn->query($sql);

if($result->num_rows > 0){
  while($row = $result->fetch_assoc()){
    echo  json_encode(array("hsnNo"=>$row['hsn'], "qty"=>$row['quantity']));
  }
}

}

?>

我该怎么做才能为每一行设置字段的值?

0 个答案:

没有答案