简体   繁体   中英

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/

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);
    });
})();


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM