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

152

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

Answer

Solution:

An HTML element'sid is supposed to be unique; you have given multiple elements the sameid, 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 inaddCart():

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>



753
votes

Answer

Solution:

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



People are also looking for solutions to the problem: cannot use isset() on the result of an expression (you can use "null !== expression" instead)
Source

Share


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

556 PHP MySQL JOIN tables, while loop
963 php - $.getJSON returning null
283 PHP SQL Allow empty or numeric input field
213 php - User admin status isn't being remembered (admin area disappears after a while)
581 php - Count surplus entries of duplicate values in an array
196 Get JSON objects in PHP, not array
617 php - JSON Android App, Retrieval of data issue
3 Javascript, PHP json will not parse?
693 How to merge two JSON Objects into one in php?
350 php - Exception 'could not find driver' while migration in yii2
753

Answer

Solution:

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

People are also looking for solutions to the problem: javascript - Any HTML to PDF renderers that offer adjustable dpi, selectable text, and CSS support?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.