How can I send data to admin-ajax via JS Fetch?

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,

  1. 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().

  2. 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 ) );

Leave a Comment