0

I would send data (POST method) and fetch that in fetch. Problem is that I send data via axios or jQuery, I can see this var like $_POST. In fetch not. Look at this example script.js

const update = {
    title: 'A blog post by Kingsley',
    body: 'Brilliant post on fetch API',
    userId: 1,
};
const options = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(update),
};

fetch('test.php', options)
    .then(data => {
        return data.json();
    })
    .then(post => {
        console.log(post);
    });

test.php

<?php
    print_r(json_encode($_REQUEST));

In console.log, it displays an empty array. How can I send and fetch post data via fetch?

  • 1
    If you use `'Content-Type': 'application/json'`, the $_POST super global won't automatically be populated. You need to fetch the raw body and decode it yourself: `$data = json_decode(file_get_contents('php://input'), true);` – M. Eriksson Oct 11 '21 at 05:47
  • 1
    Does this answer your question? [Receive JSON POST with PHP](https://stackoverflow.com/questions/18866571/receive-json-post-with-php) – M. Eriksson Oct 11 '21 at 05:48
  • instead of body: JSON.stringify(update), i think you have to sent data: JSON.stringify(update) then you will find data array.Thanks – Hassan ALi Oct 11 '21 at 06:16
  • @HassanALi - Not when you're using `fetch()`: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_json_data – M. Eriksson Oct 11 '21 at 06:25

0 Answers0