简体   繁体   中英

How to get value of buttons in a PHP foreach loop in Javascript

I'm working on a very simple social media webapp to practice PHP & Ajax. Users get some friend suggestions, and when they send a request I want the recipient to get a little notification using Ajax.

The request button is in a foreach loop, like so:

<?php foreach ($suggestions as $suggestion) : ?>
   [...]
   <form action="" method="post" id="formRequest">
      <input type="hidden" name="userID" class="userID" value="<?php echo $userID ?>">
      <input type="hidden" name="buddyID" class="buddyID" value="<?php echo $suggestion['userID'] ?>">
      <input type="submit" value="Add as friend" name="request" class="request">
   </form>

To test if Ajax gets the right buddyID value when I click 'Add' a specific user, I have tried this:

let request = document.querySelector(".request");

   request.addEventListener("click", function() {
      let buddyID = document.querySelector(".buddyID").value;
      console.log(buddyID);
   })

but this only logs the first suggested buddy's ID (so only when I click the first button); the console stays empty when I add the 2nd or 3rd suggested buddy. My guess is I'll have to use a for loop, but when I tried to add one it wouldn't print anything at all.

In order to assign the click event listener to all the buttons rather than just to one you could try something like this using querySelectorAll to find the nodelist through which you iterate.

Array.from( document.querySelectorAll( 'input[type="submit"].request' ) ).forEach( bttn=>{
    bttn.addEventListener('click',(e)=>{
        e.preventDefault();

        let buddyID=e.target.parentNode.querySelector('.buddyID').value;
        let userID=e.target.parentNode.querySelector('.userID').value;

        console.info( buddyID, userID );
    });
});

You could simplify things further by removing the forms ( which don't really do anything here anyway if you use AJAX ) and simply have a singular button per record / suggestion that has the necessary information assigned to it in the form of dataset attributes.

<?php
    foreach( $suggestions as $suggestion ) { 
?>

    <input class="request" type='button' data-buddyID="<?php echo $suggestion['userID'];?>" data-userID="<?php echo $userID;?>" value="Add as friend" />

<?php
    }
?>



Array.from( document.querySelectorAll( 'input[type="button"].request' ) ).forEach( bttn=>{
    bttn.addEventListener('click',function(e){
        e.preventDefault();

        let buddyID=this.dataset.buddyID;
        let userID=this.dataset.userID;

        console.info( buddyID, userID );
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM