从组合框中选择索引时更改文本框值

时间:2016-08-24 01:34:39

标签: javascript php html

我有一个组合框,其中包含从数据库中提取的数据。从组合框中选择索引时,文本框值将从数据库中获取值,具体取决于从组合框中选择的索引。我有以下代码。

<form action = '' method = "POST">
  <b> School ID: </b><br />
  <select name = "school_id" required id = "schoold_id" onchange="get_data(this.value)">
  <option value = "" selected></option>
  <?php 
  $sql = "SELECT DISTINCT school_id FROM school";
  $result = $db->query($sql);
  if ($result->num_rows > 0){
        while($row = $result->fetch_assoc()){
              echo "<option value = ".$row["school_id"].">".$row["school_id"]."</option>";
        }
  }
  ?>
  </select><br /><br />
  <b> Batch Number: </b><br />
  <input type= "text" name = "batch_no" /required><br /><br />
  <b> School Name: </b><br />
  <input type= "text" name = "school_name" /readonly><br /><br />
  <input type = "submit" value = " Submit "/><br />
  </form>

这里的组合框是学校ID,需要更改的文本框是学校名称。

我尝试使用javascript,这是我使用的。

<script>
function get_data(value){
$.ajax({
    url: "ajax.php",
    type: "POST",
    dataType: "HTML",
    async: false,
    data: {value: value}
    success: function(data) {
       //here we can populate the required fields based on value from database                
    }
 });
}</script>

这是ajax文件

<?php
include "connect.php";
$myschoolid = (filter_input(INPUT_POST, 'school_id'));

$sql = $db->prepare('SELECT school_name FROM main where school_id = ?');
$sql->bind_param('i', $myschoolid);
$sql->execute();
$result = $sql->get_result();
if ($result->numrows >0){
    while ($row = $result->fetch_assoc()){
        $newschoolid = $row["school_name"];
    }
    echo $newschoolid;
}
?>

我可能在这里做错了什么。我对ajax并不完全熟悉。非常感谢帮助。

0 个答案:

没有答案