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条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历