Reputation: 107
I'm trying to submit a form with jQuery's $.ajax() function and it works, aside from the fact that it only sends the value of the last of several checkboxes, regardless of how many I check. I'd appreciate if someone could tell me what I'm doing wrong. Thanks in advance!
The HTML form:
<form name="contactFormSmall" id="contactFormSmall" action="" method="post">
<input type="text" name="textfieldname" value="textfieldvalue" />
<input type="checkbox" name="checkboxes" value="Testvalue One" checked="checked" />
<input type="checkbox" name="checkboxes" value="Testvalue Two" checked="checked" />
<input type="checkbox" name="checkboxes" value="Testvalue Three" checked="checked" />
</form>
Here's the jQuery handling the form:
var fields = $(":input").serializeArray();
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
url: "includes/contact_process_small.php",
data: fields,
success: function(data) {
$('#contactFormSmall').hide();
$("#formFeedback").html(data).show();
}
});
And here's the result from print_r($_POST) in the php script:
Array
(
[textfieldname] => textfieldvalue
[checkboxes] => Testvalue Three
)
Upvotes: 2
Views: 1117
Reputation: 1057
The name attribute is the key in the key value pair of the POST data. So use either name="checkboxes[]" to create an array or use:
<form name="contactFormSmall" id="contactFormSmall" action="" method="post">
<input type="text" name="textfieldname" value="textfieldvalue" />
<input type="checkbox" name="checkboxA" value="Testvalue One" checked="checked" />
<input type="checkbox" name="checkboxB" value="Testvalue Two" checked="checked" />
<input type="checkbox" name="checkboxC" value="Testvalue Three" checked="checked" />
</form>
to obtain the value of each checkbox individually (which is more likely to be what you want).
Upvotes: 0
Reputation: 149
better way serialize form
like this
data: $('#contactFormSmall').serialize(),
and change to name="checkboxes[]
Upvotes: 0
Reputation: 3025
name="checkboxes"
is correct only on a single element, you have to use name="checkboxes[]"
.
Upvotes: 6