dongxiansi0158 2018-05-17 14:54
浏览 82
已采纳

使用JS获取PHP while循环中包含的输入字段的值

I have an input box wrapped in a while loop, so i displays the ID or items in the database. Thus i have input boxes as 001,002,003,004,005 ... and I have a button below each input box.

What i want

1) When i click on a button, i want JS to log the value of the corresponding input box for example if I click on the button below input box 003, js should display 003.

2) I also want to use Ajax to send that value to database via (sendajax.php) and on success it should display a div with a message.

What I'm Getting

I keep getting 001 no matter the button i click on.

The Code

<?php
$booksSql = "SELECT * FROM tblitems";
$getBooks = mysqli_query($con, $booksSql);
while($row = mysqli_fetch_assoc($getBooks)){
$id = $row["itemid"];
?>



<form>
<input id="itemID" name="itemID"  type="text" value="<?php echo $id;  ?>">
<!--it display 001, 002, 003, 004 in the input boxes as it should-->
<input id="submit" onclick="addCart();" type="button" value="Submit">
</form>



<?php
}
?>


<script>
function addCart(){
        var input =  document.getElementById('itemID').value;
        console.log(input);
        //but this keeps displaying 001, no matter which button i click
}
</script>

My current sendajax.php

    include("dbconn.php");

    $id = $_POST["id"];


    if (isset($_POST['id'])) {
        $send = "query to insert to db";
    $query = mysqli_query($con, $send);
    }
  • 写回答

2条回答 默认 最新

  • douya2006 2018-05-17 15:05
    关注

    The comments about duplicate IDs are absolutely correct and probably the only issue with your existing code, but I'd recommend also not parsing the DOM for a value that you can just pass to the function when you call it, like this...

    PHP

    <input id="something-unique" name="something-unique" type="text" value="<?php echo $id; ?>">
    <input id="submit" onclick="addCart('<?php echo $id; ?>');" type="button" value="Submit">
    

    Javscript

    function addCart(itemId){
        // send the itemId to a php page...
        $.ajax({
            url: "sendajax.php?itemId=" + itemId
        })
        .done(function(data) {
            // you may want to check the value of 'data' here - if you return anything from PHP
            alert("value sent");
        })
        .fail(function() {
            alert("There was a problem sending the data");
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.