Sure.
You’ll still need to attach an onchange event handler to the checkboxes, so that an AJAX request is fired every time a user selects or deselects anything:
// This selects the checkboxes
var $checkboxes = $( "input:checkbox" );
$checkboxes.on("change", function(){
// Code here will be executed whenever a user selects or deselects a check box
})
When your AJAX request hits your PHP script, your PHP script will be expecting two arrays: “fruit” and “price”
So when the onchange code is executed we will need to construct these arrays:
$checkboxes.on("change", function(){
var fruit = [],
price = [];
$checkboxes.each(function(){
if (this.checked){
if(this.name === "fruit[]"){
fruit.push(this.value);
} else if (this.name === "price[]"){
price.push(this.value);
}
}
})
Once the price and fruit arrays are populated correctly, all that is left to do is to send them off to the PHP script via AJAX.
I would make this a separate function:
function makeAjaxRequest(fruit, price){
$.ajax({
type: "POST",
url: "submit.php",
cache: false,
data: {fruit: fruit, price: price},
success: function(result){
// This code will fire when the AJAX request completes successfully.
// result will contain the server's response
}
});
}
$checkboxes.each(function(){
...
makeAjaxRequest(fruit, price);
})
And that should be all there is to it
Here’s the complete code:
index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Fruity AJAX 3</title>
<link href="" rel="stylesheet" type="text/css">
</head>
<body>
<form method="post" action="submit.php" id="myform">
<div class="item">
<input type="checkbox" name="fruit[]" value="melon">melon
</div>
<div class="item">
<input type="checkbox" name="fruit[]" value="kiwi">kiwi
</div>
<div class="item">
<input type="checkbox" name="price[]" value="expensive">expensive
</div>
<div class="item">
<input type="checkbox" name="price[]" value="cheap">cheap
</div>
<input type="submit" value="select">
</form>
<div id="result"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function makeAjaxRequest(fruit, price){
$.ajax({
type: "POST",
url: "submit.php",
cache: false,
data: {fruit: fruit, price: price},
success: function(result){
$("#result").text("The server recieved the following values: " + result)
}
});
}
var $checkboxes = $( "input:checkbox" );
$checkboxes.on("change", function(){
var fruit = [],
price = [];
$checkboxes.each(function(){
if (this.checked){
if(this.name === "fruit[]"){
fruit.push(this.value);
} else if (this.name === "price[]"){
price.push(this.value);
}
}
})
makeAjaxRequest(fruit, price);
})
</script>
</body>
</html>
submit.php
<?php
print_r($_POST);
?>