脚本不会将信息从下拉列表发布到文本框

时间:2016-05-28 05:44:46

标签: javascript php jquery

我正在尝试从下拉列表中获取数据并将其发布到文本框中。但由于某种原因,我也没有得到任何响应,需要在文本框中显示Error消息。

首先,这是我的下拉列表:

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

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

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

 if ($result->num_rows > 0) {
  echo "<select class='form-control' id='product1' name='product1' onChange='getProduct1(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["article_id"]. " | " . $row["name"]. "</option>";
   }                   
  echo "</select>";
  } else {
  echo "0 results";
  }
 $conn->close();
?>  

在下拉列表中选择项目后,脚本需要将. $row["name"].粘贴到以下文本框中:

<input type="text" class="form-control" id="product11" name="product11">

我用来粘贴名称的jquery脚本是以下脚本:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> 
 function getProduct1(selectedItem) { // Do an Ajax request to retrieve the information 

 console.log("getProduct1 before ajax", jQuery('#product1').val());
 jQuery.ajax({ 
  url: 'get.php', 
  method: 'POST', 
  data: {'product1' : jQuery('#product1').val()},
  success: function(response){ 
   // and put the price in text field 
   console.log("getProduct1 after ajax", jQuery('#product1').val());
   jQuery('#product11').val(response);

   }, 
  error: function (request, status, error) { 
   alert(request.responseText); 
   }, 
  }); 
 } 
</script>

该脚本使用以下与数据库连接的PHP脚本并检索相关信息:

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

 // Create connection
 $conn = new mysqli($servername, $username, $password, $dbname) ;
 // Check connection
 if ($conn->connect_error) {
  die('Connection failed: ' . $conn->connect_error) ;
  }else {
  $product1 = isset($_POST['produc1t'])?$_POST['product1']:'';
  $product11 = isset($_POST['product11'])?$_POST['product11']:'';

  $query = 'SELECT * FROM products WHERE id="' . mysqli_real_escape_string($conn, $product1) . '"';    
  $res = mysqli_query($conn, $query) ;
  if (mysqli_num_rows($res) > 0) {
   $result = mysqli_fetch_assoc($res) ;
   echo $result['product11'];   
   }else{
   $result = mysqli_fetch_assoc($res) ;
   echo "Error";   
  }    
 } 
?>

当我通过在下拉列表中选择一个选项来运行脚本时,没有任何事情发生。有谁知道我的剧本有什么问题?

1 个答案:

答案 0 :(得分:1)

我不确定您是否应该再次查询数据库以获取已检索的值。这样的事情应该有效:

jQuery( document ).ready(function() {
    jQuery( "#product1" ).change(function(){
        var name = jQuery( "#product1 option:selected" ).text().split('|')[1];
        jQuery("#product11").val(name);
    });
 });

您不需要HTML中的javascript / jQuery命令