Reputation: 3091
I have two rows of check-boxes. When a user clicks on any individual check-box (in a certain row) I want to add a number to my sum in PHP. If he deselects an individual check-box I want to subtract from the total in real time without page refresh. My question what goes in the data field on my AJAX call?
and is this the correct way to do it ?
<input type="checkbox" name="standard_form[]" value="A" onclick="processForm()">
<input type="checkbox" name="premium_form[]" value="B" onclick="processForm()">
<script type="text/javascript">
function processForm() {
$.ajax( {
type: 'POST',
url: 'submit_form.php',
data: '',
success: function(data) {
$('#message').html(data);
}
} );
}
</script>
if(IsChecked('standard_form','A'))
{
$price += IsChecked('standard_form','A') ? 10 : 0;
}
return $price ;
Upvotes: 2
Views: 9033
Reputation: 92334
You have to serialize the form into a JS object, that's what goes into the data field. Here's a simple serialize function, that could be improved, but will give you an idea
function serializeForm(form) {
var obj = {};
for (var i = 0; i < form.elements.length; i++) {
var el = form.elements[i];
if (el.name) {
if (obj[el.name] && obj[el.name].constructor == Array ) {
obj[el.name].push(el.value);
} else if (obj[el.name]) {
obj[el.name] = [obj[el.name], el.value];
} else {
obj[el.name] = el.value;
}
}
}
return obj;
}
There is a plugin that lets you submit forms with AJAX easily http://jquery.malsup.com/form/ See jQuery AJAX submit form
Assuming the following HTML
<form id="myForm" action="submit_form.php" method="post">
<input type="checkbox" name="standard_form[]" value="A" onclick="processForm()">
<input type="checkbox" name="premium_form[]" value="B" onclick="processForm()">
</form>
You can just do the following to have the form posted with AJAX
// attach handler to form's submit event
$('#myForm').submit(function() {
// submit the form
$(this).ajaxSubmit();
// return false to prevent normal browser submit and page navigation
return false;
});
Upvotes: 1
Reputation: 4247
In checkboxes try onclick="processForm(this)"
, then, in JavaScript:
<script type="text/javascript">
function processForm(elm) {
$.ajax( {
type: 'POST',
url: 'submit_form.php',
data: elm.name+'='+elm.value,
success: function(data) {
$('#message').html(data);
}
} );
}
</script>
Upvotes: 0
Reputation: 5239
Try:
<script type="text/javascript">
function processForm() {
$.ajax( {
type: 'POST',
url: 'submit_form.php',
data: { checked_box : $('input:checkbox:checked').val()},
success: function(data) {
$('#message').html(data);
}
} );
}
</script>
Upvotes: 2