hey guys I have a problem when I select more than one checkbox the serialize from doesn't put them in an array here is the result
product-category=29&product-category=27
and I want it to be like that
product-category=29,27
this is my php code:
<form id="myform">
<fieldset>
<label>Categorys</label>
<?php
$cats = get_terms([
'taxonomy' => 'product_cat',
'hide_empty' => false,
]);
?>
<?php foreach($cats as $cat) : ?>
<input type="checkbox" id="product-category-checkbox" name="product-category" value="<?php echo $cat->term_id; ?>">
<?php endforeach; ?>
</fieldset>
</form>
and this is the js code:
<script>
(function($){
$(document).ready(function(){
$(document).on('submit', '#myform', function(e) {
e.preventDefault();
var data = $(this).serialize();
console.log(data);
var settings = {
"url": "<?php echo WC_AJAX::get_endpoint( 'kia_search' ) ?>",
"method": "POST",
"data": data
}
$.ajax(settings).done(function (response) {
$('.products').html(response);
});
});
});
})(jQuery);
</script>
CodePudding user response:
Instead of serializing the data directly via .serialize()
, you should instead use .serializeArray()
to get the data as an array. You can manipulate the array and then serialize it with $.param()
.
So change
var data = $(this).serialize();
To this instead
var data = $(this).serializeArray();
// get 'product-category` values from array and join them
var categories = data.filter(obj => obj.name === 'product-category').map(obj => obj.value).join(',');
// add the joined 'product-category' back to data
if( categories.length > 0 ){
data = data.filter(obj => obj.name !== 'product-category')
.concat({name: 'product-category', value: categories});
}
// serialize data
data = $.param(data);
CodePudding user response:
You'll need to manually serialize the array to your desired format. The basic idea is to collect all checked checkboxes, iterate over them and get the checkbox value, then join()
the values together.
The below example uses jQuery map()
to loop over the checkboxes and return the value.
$(document).on('submit', '#myform', function(e) {
e.preventDefault();
let data = '';
// get all checked checkboxes
let checkboxes = $(':checkbox:checked');
if (checkboxes.length > 0) {
data = 'product-category=';
// get the checkbox value and join values together
data = checkboxes.map(function() {
return this.value;
})
.get()
.join(); // joins using ',' by default
console.log(data);
// your ajax request
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="checkbox" name="product-category" value="1">
<input type="checkbox" name="product-category" value="2">
<input type="checkbox" name="product-category" value="3">
<input type="submit" value="click" />
</form>