PHP和Ajax:为什么我的可靠下拉列表不起作用?

时间:2019-07-12 20:44:19

标签: php jquery ajax mysqli

我正在尝试在我的php中编写两个可靠的下拉列表,国家和城市,其中城市应该基于第一个下拉列表的值,国家。当第一个下拉列表按预期工作时,第二个为空。我的ajax函数无法正常工作。这是main.php和hscity.php,其中包含第二个下拉列表的mysqli查询。

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="charset=utf-8" />
<title>Enter student info</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> 
</script>
<script type="text/javascript">
function fetch_select(val)
{
  $.ajax({
  type: 'post',
  url: 'hscity.php',
  data: {
  get_option:val
  },
  success: function (response) {
  document.getElementById("hscity").innerHTML=response; 
  }, 
  error : function ($responseObj){
         alert("Something went wrong while processing your request.\n\nError => "
             + $responseObj.responseText);
     }
  });
}
</script>

</head>
<body>
<p>
<label for="hscountry">
<select name='hscountry' id = 'hscountry' onchange = 
"fetch_select(this.value);">
<option selected disabled>Please select from below</option>
<?php

    $host = 'myhost';
    $username = 'myusername';
    $password = 'mypassword';
    $database = $username.'DB';

    $dbcon = mysqli_connect($host, $username, $password, $database)
       or die('Could not connect: ' . mysqli_connect_error());
    print 'Connected successfully!<br>';


    $query1 = "SELECT DISTINCT country FROM highschools";
    $result1 = mysqli_query($dbcon, $query1)
      or die('Query failed: '. mysqli_error($dbcon));
    while ($row = mysqli_fetch_array($result1)) {
        echo "<option value='" . $row['country'] . "'>" . $row['country'] . "</option>";
    }
    mysqli_free_result($result1);
    mysqli_close($dbcon);
?>
</select>
</label>

<select id = 'hscity'>
<option selected disabled>Please select from below</option>
</select>

这是hscity.php:

{
<?php
if(isset($_POST['get_option']))
{
$host = 'myhost';
$username = 'myusername';
$password = 'mypassword';
$database = $username.'DB';
$hscountry = $_POST['get_option'];



$dbcon = mysqli_connect($host, $username, $password, $database)
    or die('Could not connect: ' . mysqli_connect_error());
    print 'Connected successfully!<br>';

$query2 = "CALL gethscities('$hscountry')";
$result2 = mysqli_query($dbcon, $query2)
    or die('Query failed: ' . mysqli_error($dbcon));

while ($row = mysqli_fetch_array($result2)) {
        echo "<option value='" . $row['city'] . "'>" . $row['city'] . "</option>";
}

mysqli_free_result($result2);
mysqli_close($dbcon);
exit; 
}
?>

我希望第二个下拉菜单是基于所选国家/地区的列表,但实际的下拉菜单为空。

1 个答案:

答案 0 :(得分:1)

您在hscity.php上的PHP脚本失败。创建另一个DIV并在其中打印响应的内容,而不是#hcity select来查看错误输出,如果,您的PHP配置为打印任何类型的错误;否则,将以下内容添加到hscity.php的开头:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

您也可以通过在“网络”标签打开的情况下重新加载页面来检查开发人员工具,以检查响应,如注释所示。