使用jqueryonchange事件从数据库获取值

wyyhbhjk  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(302)

我有一张table上的房间清单和租金。房间在下拉菜单中列出,我想在“输入”字段值、“页面加载”以及“下拉值更改”中获取租金。我写了下面的代码,但不知怎么的,它不是预期的工作。有人能帮我吗?

<?php
define("HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "testdb");

$conn = mysqli_connect(HOST, DB_USER, DB_PASS, DB_NAME);

if (!$conn) {
  die(mysqli_error());
}
$ajax = false;
$dbValue = 1; //or the default value of your choice - matched to the default selection value of the dropdown
if (isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['dd'])) {
  $dbValue = intval($_GET['dd']);
  $ajax = true;
  $res = mysqli_query($conn, "SELECT rent FROM `rooms` WHERE roomid = '$dbValue' limit 1");
  $dataTable = '';
  while ($data = mysqli_fetch_assoc($res)) {
    $dataTable = $data['rent'];
  }
}
// if ($ajax) return $dataTable;

?>
<html>
<head>
    <title>jQuery Validation for select option</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>

<body>
    <select class="form-control" id= "roomid" name="roomid" required="">
                          <?php
                          $troom_sql = "SELECT roomid FROM rooms WHERE (isactive='y' AND isassigned='n' AND roomid NOT IN (SELECT roomid from roomalloc))";
                          $troom_rs = mysqli_query($conn, $troom_sql);
                          while ($troom_mem = mysqli_fetch_assoc($troom_rs)) {
                            ?>
                          <option value="<?php echo $troom_mem['roomid']; ?>"><?php echo $troom_mem['roomid']; ?></option>
                          <?php
                        } ?>
                        </select>
                        <input type="text" placeholder="Monthly Rent" class="form-control" id="rent" name="rent" required>

                        <br>

</body>

<script>
    $('#roomid').change(function()
    {
        var first = $('#roomid').val();
        var req = $.get('getDB.php', {dd: first, action: 'ajax'});
        req.done(function(data)
        {
          console.log("asdasd");
          $('#rent').val("<?php echo $dataTable; ?>");
        });
    });
</script>

</html>
23c0lvtd

23c0lvtd1#

创建一个jqueryajax函数,该函数接受post/get请求的参数,并在jquery事件上调用该ajax函数。ajax函数应该是这样的,

function LoadComponentPage( param ){
    $.ajax({
        type: "POST",
        url: "./controller/ajax/component_paginate.php",
        data: "page="+param,
        dataType: "text",
        success: function(resultData){
            let section = $('#ComponentsListing');
            section.empty();
            section.html(resultData);
        },
        error : function(e){
            console.log(e);
        }
    });
}

并在事件发生时调用该函数 onclick="LoadComponentPage(param)" . 您可以对调用的结果进行后处理以显示结果或错误,如示例函数所示。

vsaztqbk

vsaztqbk2#

虽然您已经在同一个文件中编写了php和js,但是仍然需要从php端返回数据并在js中处理。

if ($ajax) return json_encode($dataTable)

从php端

dat = JSON.parse(data)

在js中

相关问题