duanjiu1003 2017-02-20 14:28
浏览 24
已采纳

来自select表单的Ajax请求

I'm trying to pull a value from my database when a select value is selected. This select is also populated from the same database.

To be clear, I'm new to AJAX requests and don't really understand what I'm doing wrong. All I get is blank when a value should appear.

This is my html form:

function showStock(str) {
    if (str == "") {
        document.getElementById("stockValue").innerHTML = "";
        return;
    } else {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("stockValue").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "getstock.php?q=" + str, true);
        xmlhttp.send();
    }
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>

    <?php $link=mysqli_connect( "localhost", "root", "", "cocktails"); // Check connection if($link===f alse){ die( "ERROR: Could not connect. " . mysqli_connect_error()); } ?>

    <script src='menu.js'></script>

    <form action="addstock.php" method="post">
        Product:
        <br>
        <select name="products" onChange="showStock(this.value)">
            <option value="">Select a product:</option>
            <?php $sql=m ysqli_query($link, "SELECT name FROM inventory ORDER BY name"); while ($row=$ sql->fetch_assoc()){ echo "
            <option value=\ "".$row[ 'name']. "\">" . $row['name'] . "</option>"; } ?>
        </select>
        <br> Stock Value:
        <div id="stockValue">
            <b>0</b>
        </div>

    </form>
</body>

</html>

This is my php file:

<!DOCTYPE html>
<html>

<head> </head>

<body>
    <?php
        $q = intval($_GET['q']);

        $con = mysqli_connect('localhost','root','','cocktails');
        if (!$con) {
            die('Could not connect: ' . mysqli_error($con));
        }

        $sql="SELECT * FROM inventory WHERE name = '".$q."'";
        $result = mysqli_query($con,$sql);
        $row = mysqli_fetch_array($result);

        echo $row['stock'];
        mysqli_close($con);
        ?>
</body>

</html>
</div>
  • 写回答

3条回答 默认 最新

  • dquh37673 2017-02-20 15:46
    关注

    Well It wasn't that evident but your problem is :

    $q = intval($_GET['q']);
    

    your $_GET['q'] is a string and you are converting it to an intval so it becomes a 0.

    And your SQL query is getting nothing because of that.

    Change this line to $q = $_GET['q']; and it will work :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题