Jane Doe Jane Doe - 7 months ago 14
jQuery Question

ajax request of form not returning expected data

I have a form that contains checkboxes, radio buttons, and text area's. Then I have three buttons, regardless of what button is clicked it should call on the same php file to handle the form data. I need to keep track of which button is pressed, because the form data is handled differently depending on the button that is pressed.

I want this to update the page without reloading or redirecting and I am having trouble with getting the ajax to work properly. The php file just contains: "

<pre><?php print_r($_POST); ?></pre>
"at the moment, I will implement a switch-case after I have the basic functionality working.

When a button is clicked, a duplicate of the form is generated on the page instead of returning the POST values.

<form id="form" action="calc.php" method="post">
<input type="radio" name="rb[]" value="one" checked> one<br>
<input type="radio" name="rb[]" value="two">two<br>
Option a<input type="checkbox" name="cb[]" value="a">
Text a<input type="text" name="tb[]">
Option b<input type="checkbox" name="cb[]" value="b">
Text b<input type="text" name="tb[]">
<button id="first" class="button" name="button[]" value="first">first</button>
<button id="second" class="button" name="button[]" value="second">second</button>
<button id="third" class="button" name="button[]" value="third">third</button>

$('.button').click(function(e) {
var f = $('form').serialize();
var b = this.id;
data: {'button':b, 'formval': f},
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(resp){
return false;

How can I send the form values as an array along with the button that was clicked to the php file, and then have it return the result of the php file on the page?

Thank you.


You can use $.serializeArray and append to the returned array in the following manner:

$('.button').click(function(e) {
    var $form = $('form');
    var data = $form.serializeArray();

    data.push({ 'name': 'button', 'value': this.id }); // append button's ID

        data: data,
        type: $form.attr('method'),
        url: $form.attr('action'),
        success: function(resp){
    return false; // I don't think this is needed since your button is type="button"