I’m trying to implement filter system in my website. I decided to make it via js. I created fetch function
let filters = document.querySelectorAll('.filters-item');
let pageUrl = wp.page_url;
const postsContainer = document.querySelectorAll('.column.is-half.is-offset-1');
filters.forEach( (item) => {
item.addEventListener('change', (e) =>{
let url = pageUrl + '/wp-admin/admin-ajax.php';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'text/html; charset=UTF-8',
},
body: JSON.stringify({
'test': "sampledatatest",
})
}).then( function (response) {
if(response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.warn('Error', error);
});
});
});
In my functions.php file I have simple function
add_action('wp_ajax_myfilter', 'misha_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
function misha_filter_function(){
$t = $_POST['test'];
echo $t;
die();
}
When I click on filter
item I’m getting error 400 in my dev console. What am I missing? Is it proper way to pass the data in the form like I did? I don’t want to use jQuery.