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>
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 remove below line, and make it more dynamic
var data = $(this).serialize();
Like so. This is to ensure that, even if more form elements are added later, there will be no need to alter the code.
<script>
(function($){
$(document).ready(function(){
$(document).on('submit', '#myform', function(e) {
e.preventDefault();
// get data
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);
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>