Click here to Skip to main content
15,887,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to pass a name parameter of a button using AJAX POST method to a PHP file.

I am getting an error after submitting the form with Ajax that the index is undefined on the page 2.

What I have tried:

The HTML form:

<form class="upVote" action=""  method="post">
<button id="plus" name="plus" value="foo">button</button>
</form>';


The AJAX:

$(document).ready(function(){
  $(".upVote").submit(function(){
      $.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 PHP POST:

$_POST['plus'];
Posted
Updated 21-May-19 7:46am

1 solution

No submit button value is serialized since the form was not submitted using a button.

Since you only have a single button in your form, the simplest solution is to remove its name attribute, and move the value to a hidden input.
HTML
<form class="upVote" action="../inc/handlers/up-vote.php"  method="post">
    <input type="hidden" name="plus" value="foo" />
    <button type="submit">button</button>
</form>
 
Share this answer
 
Comments
Galarist_00 21-May-19 16:20pm    
It does the trick! :) What can I do if I have a foreach loop for the forms and each input contains different values? In this situation the Ajax only send one value. If I do it for a single input it works perfectly.
Richard Deeming 22-May-19 7:15am    
Sorry, I don't understand what you mean.
Galarist_00 22-May-19 7:25am    
I have a foreach loop on the page 1 and it displaying all the forms for each data. I want to send the value from the particular form that I have submitted. Every value is different.
Richard Deeming 22-May-19 7:26am    
Do you still have a single value per form? If so, a hidden input will still work.
Galarist_00 22-May-19 7:26am    
I just asked a question about that. https://www.codeproject.com/Questions/4532857/How-do-I-pass-value-from-foreach-loop-with-AJAX-to

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