staynjokede
staynjokede

Reputation: 97

Use JS to get value of input field wrapped in a PHP while loop

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);
    }

Upvotes: 1

Views: 864

Answers (2)

user5734311
user5734311

Reputation:

An HTML element's id is supposed to be unique; you have given multiple elements the same id, which is why your function simply grabs the first element.

Instead of a <form> and multiple inputs, use just this:

<input type="button" onclick="addCart(this.value);" value="<?= $id ?>">

Now you can grab the id in addCart():

function addCart(idString) {
    console.log(idString);
}

Edit: It should be noted that I avoid inline code wherever possible and would use jQuery instead, something like

$(function() {
  $("#items input").on("click", function() {
    console.log(this.value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="items">
  <input type="button" value="001">
  <input type="button" value="002">
  <input type="button" value="003">
  <input type="button" value="004">
  <input type="button" value="005">
</div>

To POST the id, use something like:

fetch("sendajax.php", {
  method: "post",
  headers: new Headers({
    "Content-Type": "application/x-www-form-urlencoded"
  }),
  body: "id=" + Number(idString)
}).then(response => response.text()).then(text => {
  alert(text);
});

Upvotes: 3

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

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");
    });
}

Upvotes: 2

Related Questions