从下拉列表中的选定值填充文本框

时间:2016-02-19 14:44:55

标签: php sql ajax

我有一个名为product1的下拉列表和一个名为price1的文本框。下拉列表中填充了products数据库。我想在名为'price1'的文本框中显示所选price的{​​{1}}。

我使用的是以下表结构:

product

使用以下代码,我试图用所选值填充文本框。

forms (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sort` int(1) NOT NULL,
  `name` varchar(100) NOT NULL,
  `prices` decimal(7,2) NOT NULL,
  `tax` int(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

当我在下拉列表中选择产品时,没有任何事情发生。

任何人都可以帮我修复此代码吗?

谢谢!

更新1:仍无效

//filename: test.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

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

if ($result->num_rows > 0) {
     echo "<select class='form-control select2' id='product1' name='product1' onChange='getstate(this.value);' style='width: 100%;'>";
     echo "<option selected disabled hidden value=''></option>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
                      echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
     }                   
echo "</select>";
} else {
     echo "0 results";
}

$conn->close();

?>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM forms WHERE id='". $product1 ."'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {

          echo "<div id='price-list'>";
              echo "<input type='text' class='form-control' name='price1' id='price1' value='" . $row["price"]. "'>";
          echo "</div>";

     }                   
} else {
     echo "0 results";
}

$conn->close();

?>  

<script>
         function getprice(val) {
            $.ajax({
              type: "POST",
              url: "test.php",
              data:'id='+val,
              success: function(data){
                $("#price-list").html(data);
              }
            });
          }
</script>

<?php
$product1=$_POST['price1'];
?>

//filename: index.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

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

if ($result->num_rows > 0) {
     echo "<select class='form-control select2' id='product1' name='product1' onChange='getstate(this.value);' style='width: 100%;'>";
     echo "<option selected disabled hidden value=''></option>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
                      echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
     }                   
echo "</select>";
} else {
     echo "0 results";
}

$conn->close();

?>
<html>

<!-- Your text input -->
<input id="product_name" type="text">

</html>

<script>
function getPrice() {

    // getting the selected id in combo
    var selectedItem = jQuery('.select2 option:selected').val();

    // Do an Ajax request to retrieve the product price
    jQuery.ajax({
        url: 'get.php',
        method: 'POST',
        data: 'id=' + selectedItem,
        success: function(response){
            // and put the price in text field
            jQuery('#product_name').val(response);  
        },
        error: function (request, status, error) {
            alert(request.responseText);
        },
    });
}
</script>

3 个答案:

答案 0 :(得分:0)

试试这个:

在您的选择中,您正在为 onchange 进行回调,使用它来调用javascript函数,并在此函数中获取值并填充您的文本字段。

...
<select class='form-control select2' id='product1' name='product1' 
    onchange='changeValue();' style='width: 100%;'>

<!-- Your text input -->
<input id="product_name" type="text">
...

function changeValue() {

    // getting the selected text in combo
    var selectedItem = jQuery('.select2 option:selected').text;


    // and putting in text field
    jQuery('#product_name').val(selectedItem);
}

答案 1 :(得分:0)

虽然您拥有相同的脚本 test.php ,但您可能已经介绍了您无法区分的基本问题...

  • 使用产品列表
  • 设置页面(第一次调用)的情况
  • 发布产品ID以获取价格的情况(AJAX调用,只要用户选择其他产品)。

这两种情况可以通过变量 $ _ POST [&#39; id&#39;] isset($ _ POST [ &#39; id&#39;] )。变量 $ _ POST [&#39; price1&#39;] 但绝不会传输和使用。

我一起困惑(没有经过测试)。试试吧:

<?php
//filename: test.php

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

if (!isset($_POST['id'])) { // First call: setup the page -----------------------------

    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "database";

    echo '<html>
<head>      
    <script>
     function getprice(val) {
        $.ajax({
          type: "POST",
          url: "test.php",
          data:\'id=\'+val,
          success: function(data){
            $("#price-list").html(data);
          }
        });
      }
</script>
</head>
<body>
';

    $sql = "SELECT * FROM forms";
    $result = $conn->query($sql);
    echo "<select class='form-control select2' id='product1' name='product1' onChange='getprice(this.value);' style='width: 100%;'>";
    if ( ($result!==false) && ($result->num_rows > 0) ) {
        echo "<option selected disabled hidden value=''></option>";
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
        }                   
    }
    if ($result) mysqli_free_result($result);
    echo '</select>';
    echo '<div id="price-list">';
    echo '</div>';

echo '</body>
</html>
';

} else {                    // Ajax call, $_POST['id'] is set -------------------------

    $product1 = $_POST['id'];
    $sql = "SELECT * FROM forms WHERE id='". $product1 ."'";
    $result = $conn->query($sql);
    if ( ($result!==false) && ($result->num_rows > 0) ) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<input type='text' class='form-control' name='price1' id='price1' value='" . $row["price"]. "'>";
            break;
        }                   
    } else {
        echo "0 results";
    }
    if ($result) mysqli_free_result($result);

}

$conn->close(); // Drop connection

?>

答案 2 :(得分:0)

阅读完您的评论后,我了解您所需要的是在更改组合时获得产品价格,但您仍然没有这些价格。所以你可以做一个Ajax请求来获得价格。

...
<select class='form-control select2' id='product1' name='product1' 
onchange='getPrice();' style='width: 100%;'>

<!-- Your text input -->
<input id="product_name" type="text">
...

function getPrice() {

    // getting the selected id in combo
    var selectedItem = jQuery('.select2 option:selected').val();

    // Do an Ajax request to retrieve the product price
    jQuery.ajax({
        url: 'your-php-file-to-do-query-in-database.php',
        method: 'POST',
        data: 'product_id=' + selectedItem,
        success: function(response){
            // and put the price in text field
            jQuery('#product_name').val(response);  
        },
        error: function (request, status, error) {
            alert(request.responseText);
        },
    });
}

在PHP文件中,您必须在数据库中进行查询才能获得产品价格。

$productId = filter_input(INPUT_POST, 'product_id', FILTER_SANITIZE_NUMBER_INT);

$query = 'SELECT price FROM products WHERE id=' . $productId;
//execute the query in database and return the result

// In this example I will suppose you used the mysql_* functions
// to get the price

$res = mysql_query($query);
if (mysql_num_rows($res) > 0) {
    $result = mysql_fecth_assoc($res);

    print($result['price']);

    // and finally ends the script
    die();
}

我希望这对你有所帮助。