1

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);
    }
6
  • 2
    Don't use multiple elements with the same id, for what should now be obvious reasons. Commented May 17, 2018 at 14:57
  • 2
    ID's in HTML must be unique within the document or JS will just fetch the first element it finds with that ID. You could also just add the id from PHP as an argument to your addCart() function. Commented May 17, 2018 at 14:57
  • Your <form> and </form> tags should be outside the loop unless you want to there to be a separate form for each row. Also, what Chris G and Magnus said. The problem is multiple elements with the same id... Commented May 17, 2018 at 14:58
  • I have never dealt with problem like this before, so how do i tackle this multiple element issue? Commented May 17, 2018 at 15:00
  • Give them different ID's? You have the id from PHP, just do id="ItemID-<?= $id ?>" and id="submit-<?= $id ?>. Then do as the answer below suggests and you're set. Commented May 17, 2018 at 15:00

2 Answers 2

3

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

You should also address the multiple ID-issue.
Just saw the snippet, thanks for the inline code tips. Please for the second part of the question, how do I send the idString value via an ajax POST to sendajax.php so I send sent it to database?
@staynjokede Added fetch() code to load info from server.
2

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

5 Comments

This worked !, can you please explain a little bit more why and how it works
Sure. If the value of $id is "001" then your button will trigger addCart('001');, passing the value to the function as a parameter, rather than trying to get the value later. Does that help? If you open the page in your browser and do a "view source" you'll see each of the buttons has the id value in the click event handler code.
ah silly me, I didnt notice the passing value in the function. Thank you. For the second part of the question, how can i take that itemId and send the value via ajax post to the sendajax.php page
I'll add a basic example of sending the data, but I can't help with the PHP side.
In the example I've given, you'll need to get the value of itemId in PHP, from the query string, then do whatever you need on the server with that value. If there's a problem throw an exception to cause the fail handler to execute, otherwise the done handler will execute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.