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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么