'How to post data with fetch to functions.php

I am trying to make a fetch request to the functions.php file. I am trying to avoid jQuery and Ajax thats why I am using the standard fetch API.

My code in one of my theme pages:

<button @click="load()">test</button>

And the script part in the same file:

<script>
function load() {

    fetch('<?php echo admin_url('admin-post.php'); ?>', {
            method: 'POST',
            headers: {
                'x-requested-with': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                action: 'my-action'
            })
        }).then(data => {
        console.log(data);
    })
}
</script>

The Code in my functions.php file:

add_action('wp_ajax_my_action' , 'data_fetch');
add_action('wp_ajax_nopriv_my_action','data_fetch');

function data_fetch(){
    echo "hi";
}

In the console the response works but it doesnt return anything. I think it just finds the file so it returns 200 but the data_fetch function is never executed.

How can I get this to work?

Thanks for your help ;).

I followed this post: https://www.it-swarm.dev/de/functions/ajax-live-suche-nach-posttitel/961942434/



Solution 1:[1]

i think you dont need to use specific header request for that example

also , try with FormData() :

"use strict";

(function () {
  var data = new FormData();  // create an Object and take your data
  data.append("action", "my-action");
  fetch([Object Object], { // use your ajax url instead of ***[Object Object]***
    method: "POST",
    credentials: "same-origin",
    body: data, // put your data into fetch body
  })
    .then((response) => response.text())
    .then((data) => {
      if (data) {
        console.log(data);
      }
    })
    .catch((error) => {
      console.log("[ OPS!! my_action ]");
      console.error(error);
    });
})();


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1