Monday, December 26, 2022
HomeWordPress Developmentfilters - How can I ship knowledge to admin-ajax through JS Fetch?

filters – How can I ship knowledge to admin-ajax through JS Fetch?


I am attempting to implement filter system in my web site. I made a decision to make it through js. I created fetch perform

let filters = doc.querySelectorAll('.filters-item');
let pageUrl = wp.page_url;
const postsContainer = doc.querySelectorAll('.column.is-half.is-offset-1');
filters.forEach( (merchandise) => {
        merchandise.addEventListener('change', (e) =>{
            let url = pageUrl + '/wp-admin/admin-ajax.php';

            fetch(url, {
                methodology: 'POST',
                headers: {
                    'Content material-Sort': 'textual content/html; charset=UTF-8',
                },
                physique: JSON.stringify({
                    'take a look at': "sampledatatest",
                })
            }).then( perform (response) {
                if(response.okay) {
                    return response.json();
                }
                return Promise.reject(response);
            }).then(perform (knowledge) {
                console.log(knowledge);
            }).catch(perform (error) {
                console.warn('Error', error);
            });
        });
    });

In my capabilities.php file I’ve easy perform

add_action('wp_ajax_myfilter', 'misha_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');

perform misha_filter_function(){
    $t = $_POST['test'];
    echo $t;

    die();
}

After I click on on filter merchandise I am getting error 400 in my dev console. What am I lacking? Is it correct strategy to move the info within the kind like I did? I do not wish to use jQuery.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments