Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a post system that displaying with a foreach loop. I try to implement AJAX for a button to avoid page refresh.

My real problem is when I do AJAX POST to pass a value from the PHP foreach loop then it will only pass one value from the PHP foreach loop (the last value).

I want to pass a value from a foreach loop to the page 2.

What I have tried:

The form from the foreach loop:

<form class="upVote" action="../inc/handlers/up-vote.php" method="post">
<input type="hidden" name="plus" value="'.$postIdentifier[$commentID].'" />
<button id="plus" type="submit" value="'.$postIdentifier[$commentID].'" ></button></form>


The AJAX code:

$(document).ready(function(){
$(".upVote").submit(function(){
    var plus = $(this).val();
      $.ajax({
          url: "../inc/handlers/up-vote.php",
          data: $(".upVote").serialize(),
          type: "POST",
          dataType: 'json',
          success: function (e) {
              console.log(JSON.stringify(e));
          },
          error:function(e){
              console.log(JSON.stringify(e));
              console.log('error');
          }
      });
      return false;
  });
});


The other page:
$_POST['plus'];
Posted
Updated 22-May-19 1:28am

1 solution

You need to serialize the specific form that was submitted, not every form with the upVote class.
JavaScript
data: $(this).serialize(),
 
Share this answer
 
Comments
Galarist_00 22-May-19 8:08am    
Thank you so much!!!! This really helped me out :))
[no name] 24-May-19 13:38pm    
Works for me
Richard Deeming 24-May-19 13:39pm    
This solution, or posting comments[^]?

EDIT: Of course, immediately after reporting a problem with posting comments, posting comments starts working again. 🤦‍♂️
Galarist_00 24-May-19 13:43pm    
What happened??? I am confused here lol...
Richard Deeming 24-May-19 13:46pm    
Don't worry - there was a glitch in the matrix, which resolved itself almost as soon as I reported it. 0x01AA replied to my solution as a test of the glitch. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900