添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
霸气的领结  ·  澎湃新闻·  1 月前    · 
豪爽的牛肉面  ·  舞动的归属感·  2 月前    · 
憨厚的小马驹  ·  昌邑市人民医院·  2 月前    · 

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. Visit Stack Exchange

WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.

Sign up to join this community

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

Is it possible your fetch function doesn't know about your misha_filter_function() function? Like, call the action "myfilter" anywhere? – moped Jan 25, 2021 at 9:16

Is it proper way to pass the data in the form like I did?

If you mean the body part (of your fetch() call), then yes, it is okay.

However,

  • You must send a query named action as part of the request (e.g. via the URL like example.com/wp-admin/admin-ajax.php?action=test), so that WordPress knows what AJAX action is it and then execute the callback(s) for that specific action.

    See here for further information, but in your case, the AJAX action is myfilter as in wp_ajax_myfilter and the callback is misha_filter_function().

  • The Content-Type header doesn't match the request body and you should've used application/json instead of text/html.

    But then, even with the correct request body and headers, the admin-ajax.php doesn't actually support JSON request, so if you want to send JSON request, then you should use the WordPress REST API and you'd probably want to add a custom endpoint like my-plugin/v1/myfilter.

    Otherwise, and if you prefer using the admin-ajax.php, then for example, you can use the FormData() API in JavaScript to properly build the form data to be sent to admin-ajax.php:

    var formData = new FormData();
    formData.append( 'action', 'myfilter' );
    formData.append( 'test', 'foo bar baz' );
    fetch( url, {
        method: 'POST',
        body: formData,
    } ) // wrapped
        .then( res => res.text() )
        .then( data => console.log( data ) )
        .catch( err => console.log( err ) );
                    Can you give me an example how to build custom endpoint to post multipart form data? I am new to Wordpress and I trying to integrate React form with WP.
    – Frostbourn
                    Sep 8, 2021 at 15:31
                    @Frostbourn it's not that I can't, but you should instead post your own question and not asking here.. :)
    – Sally CJ
                    Sep 10, 2021 at 13:16
                    @SallyCJ Thank you for the response. I already have done that: wordpress.stackexchange.com/questions/395462/…
    – Frostbourn
                    Sep 12, 2021 at 9:51
    

    I think below is the most convenient way to initiate an ajax request via javascript fetch API. Creating WordPress ajax requests without jQuery.

    // PHP WP ajax hook
    add_action('wp_ajax_ajaxCallback', 'ajaxCallback'); 
    
    //  Creating data 
    let requestData = {
        action: "ajaxCallback",
        myData: "Your data",
        nonce: 'test nonce'
    // Initiating AJAX request 
    fetch('http://example.com/wp-admin/admin-ajax.php', {
        method:"post",
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams(requestData).toString(),
    }).then(function(response) {
        // return response.json(); // if responce is in json.
        return response.text();
    }).then(function(response) {
        console.log(response);
            

    Thanks for contributing an answer to WordPress Development Stack Exchange!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.

  •