Reputation: 297
I have an html like this html
<input type="checkbox" class="pushchecks" value="JAN" >
<input type="checkbox" class="pushchecks" value="FEB" >
<input type="checkbox" class="pushchecks" value="MAR" >
I need to get the checked checkbox value and pass to another page by JSON format
JQUERY
$('body').on('click','.pushchecks',function(){
var bills = {}; var i=0;
$(".checks:checked").each(function(){ bills = $(this).val(); i++; });
bills = JSON.stringify(bills);
$.load('process.php', { checkedbills:bills }, '.list',function(){});
});
process.php
$billsAry = json_decode($_REQUEST['checkedbills']);
if i check JAN and MAR check box then i need to display JAN and MAR in process.php page
Upvotes: 3
Views: 58
Reputation: 2435
Just some edits to Louys Patrice Bessette code to make this work. Notice though the request here is a POST request.
test.html
<input type="checkbox" class="pushchecks" value="JAN" >
<input type="checkbox" class="pushchecks" value="FEB" >
<input type="checkbox" class="pushchecks" value="MAR" >
<!--to readable output from the php file-->
<pre class="result"><pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('body').on('click','.pushchecks',function(){
// An array.
var bills=[];
// Loop trought all .pushchecks checked.
// Edited to be .pushchecks instead of .checks
$(".pushchecks:checked").each(function(){
// Add this value in array.
bills.push( $(this).val() );
});
// Stingify the array. Would convert the array to json object
bills = JSON.stringify(bills);
// Ajax request to load process.php result in the pre tags above.
// Use $('*') to select all elements in the DOM
$('.result').load('process.php', { checkedbills:bills }, '.list',function(){});
});
</script>
process.php
<?php
$billsAry = json_decode($_REQUEST['checkedbills']);
print_r($billsAry); //The response and output to the request
?>
Upvotes: 2
Reputation: 33933
You aren't far...
The thing is that your loop was keeping the last checked value only.
Using an arry, you can make sure you collect all values.
$('body').on('click','.pushchecks',function(){
// An array.
var bills=[];
// Loop trought all .pushchecks checked.
$(".checks:checked").each(function(){
// Add this value in array.
bills.push( $(this).val() );
});
// Stingify the array.
bills = JSON.stringify(bills);
console.log(bills); // Would print : {["JAN",MAR"]}
// Ajax.
$.load('process.php', { checkedbills:bills }, '.list',function(){});
});
Upvotes: 0