Already looked through dozens of topics with the same problem, but did not find any really working solution.
JS:
/*let data = {
test_string: 'SENDED DATA',
action: 'test_ajax_func'
}*/ // already tried
let data = new FormData();
data.append('action', 'test_ajax_func');
data.append('test_string', 'SENDED DATA');
//let data_usp = new URLSearchParams(data); // already tried too, both with the object and FormData object
fetch(wp_localize_data.ajax_url, {
method: 'POST',
body: data, // JSON.stringify(data) already tried, no differecne at all
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
}
}).then(responce => {
if(responce.ok) {
console.log('ajax_request: YEP');
responce.json().then(data => console.log(data.result));
}
else {
console.log('ajax_request: NOPE');
}
}).catch(error => console.log('ERROR: ' + error));
PHP:
add_action('wp_enqueue_scripts', 'theme_styles_and_scripts');
function theme_styles_and_scripts() {
wp_register_script('ajax-test', get_template_directory_uri() . '/js/ajax-test.js', []);
wp_localize_script('ajax-test', 'wp_localize_data', ['ajax_url' => admin_url('admin-ajax.php')]);
wp_enqueue_script('ajax-test');
}
add_action('wp_ajax_test_ajax_func', 'test_ajax_func');
add_action('wp_ajax_nopriv_test_ajax_func', 'test_ajax_func');
function test_ajax_func() {
$test_string = $_POST['test_string'];
$returned_string = 'RETURNS '. $test_string;
echo json_encode(['result' => $returned_string]);
die;
}
It looks like everything should be fine, but it keeps returning 400 Bad Request.
But if I change
fetch(wp_localize_data.ajax_url, {
to
fetch(wp_localize_data.ajax_url + '?action=test_ajax_func', {
request begins to work, but PHP function does not see $_POST['test_string'] and returns just 'RETURNS ' string.
So, some truly working solution to correctly using fetch API with WordPress even exist? Cause I begin to think it's better to totally forget about it and just keep using jQuery ajax() all the time.