Having trouble sending JSON data to the server using a POST request

I am encountering an issue while attempting to send JSON data to the server using the fetch API and PHP as the server-side language. The PHP code on the server side is quite simple:

<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: PUT, GET, POST");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

    print_r($_POST);
?>

When I send the request with

"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
as follows:

fetch("http://localhost:80/test.php", {
    method: 'POST',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: "a=b"
})
.then(function(response){
    return response.text();
})
.then(function(text){
    console.log(text);
})

Everything works smoothly and the output displays:

Array
(
    [a] => b
)

However, when I attempt to send the same data in JSON format like this:

fetch("http://localhost:80/test.php", {
    method: 'POST',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: JSON.stringify({"a":"b"})
})
.then(function(response){
    return response.text();
})
.then(function(text){
    console.log(text);
})

The output shows the entire array as a key, which is unexpected:

Array
(
    [{"a":"b"}] => 
)

Changing the content type to "application/json" results in losing the output entirely and receiving an empty array:

Array
(
)

Could you please explain why this is happening and advise on how to achieve the desired outcome (sending complete data in JSON format).

Answer №1

Ensure the content-type is set to application/json:

fetch('http://localhost:80/test.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({a: 'b'})
});

The server-side code must have the ability to decode (no $_POST without form post-fields):

$array = json_decode(file_get_contents('php://input'));
echo '<pre>'.print_r($array, true).'</pre>';

The test.php file should send a content type header along with the JSON:

header('Content-type: application/json; charset=utf-8');

Answer №2

To properly format your JSON, use the following code:

JSON.stringify({a: 'Text Value', b: 1})

In your PHP script, make sure to decode the JSON data with:
print_r(json_decode($_POST));

It's important to remember that PHP won't recognize JSON data until it has been decoded.

Answer №3

Your code snippet:

fetch("http://localhost:80/test.php", {
    method: 'POST',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: {"a":"b"}
})
.then(function(response){
    return response.text();
})
.then(function(text){
    console.log(text);
})

Adjusted version:

fetch("http://localhost:80/test.php", {
    method: 'POST',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: {"a":"b"}
})
.then(function(response){
    return response.text();
})
.then(function(text){
    console.log(text);
})

Note: body: JSON.stringify({"a":"b"}) has been updated to body: {"a":"b"}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate Java and regex to convert all JSON keys to uppercase

As a newcomer to Java, I am faced with the challenge of converting all json Keys to uppercase. The JSON data I need to work with may include arrays (potentially nested) and objects. Below is an example of my input JSON: { "transactionId": 181, ...

Tips on sending arrays to PHP via HTML forms

Issue resolved, refer to my FINAL ANSWER post for a detailed explanation of the successful solution *original question and edits below: In search of a method to update multiple SQL entries using a posted array. I believe I am using PHP5. This is how I ...

The proper method for waiting for a link to be clicked using Selenium

On my web page, I have the following HTML: <a id="show_more" class="friends_more" onclick="Friends.showMore(-1)" style="display: block;"> <span class="_label">Show More Friends</ ...

Enter information into the designated text field once you have selected the button

In my PHP/HTML form for user login, I have a password field where users can enter their password or click a button to generate a random one. Although I found some JavaScript code online for this feature, I'm having trouble getting it to work with my ...

When a new ajax function is added, the original Ajax code stops functioning

I've been working on getting the code below to function properly. It seems that when I test the code, two validation functions are working correctly. However, when I include the validateUsername() function along with the if statement in the code, ever ...

Boxes that change and adapt to the user's input

Need guidance on a tricky problem! I am working on a form to input various cities that the user wants to visit. The form currently consists of one form box and a submit button. My goal is to allow the user to enter multiple cities by clicking an "Add 1 ...

What to do when encountering the error "Uncaught (in promise) SyntaxError: Unexpected end of JSON input"?

While signing in to my website from localhost is successful, I encounter an issue when trying to do the same from my production build. The login attempt from the prod build (hosted on Vercel) does not post to , but instead goes to . I am perplexed by the a ...

Issue with deploying NEXT.JS due to a failure in the build process caused by next lint

Issue I have been encountering deployment failures on Vercel due to lint errors in test files within my git repository. Despite following the recommendations from the Vercel documentation for ESLint settings, the issue persists. According to Vercel' ...

Retrieving information from a database and displaying it in JSON format as a response

Within my MySQL table, I have a set of records that I would like to fetch and display in the format of a JSON response as shown below. "results":[ { "timestamp":"2014-03-04 17:26:14", "id":"440736785698521089", "category":"spo ...

Enabling Javascript's power-saving mode on web browsers

I created a JavaScript code to play music on various streaming platforms like Tidal, Spotify, Napster, etc., which changes tracks every x seconds. If the last song is playing, it loops back to the first song in the playlist since some websites lack this fe ...

What is the best method to obtain the following id for an image?

Whenever I hover over the li with the number 3, I am getting the wrong number for the next id in the img tag. The first time, I get next id = 4 which is incorrect. But on the second hover, I get next id = 0 which is what I actually need. How can I correctl ...

Attempting to access a variable without wrapping it in a setTimeout function will

I have a form without any input and my goal is to automatically set the "responsible clerk" field to the currently logged-in user when the component mounts. Here's what I have: <b-form-select v-model="form.responsible_clerk" :op ...

How can I determine which component the input is coming from when I have several components of the same type?

After selecting two dates and clicking submit in the daterange picker, a callback function is triggered. I have two separate daterange pickers for SIM dates and Phone dates. How can I differentiate in the callback function when the user submits dates from ...

Conditional serialization in Json.NET based on the type of the object being serialized

I am aware that Json.NET allows for conditional serialization by using ShouldSerialize{PropName} Is there a way to prevent the serialization of an entire type without changing the type that references it? For example: public class Foo { public boo ...

The Invalid_grant OAuth2 error occurs when attempting to access the Google Drive API using

SOLVED! The issue was resolved by correcting the time on my Linux Server. Google's server was blocking access due to incorrect time settings. I used the following command on my Server to synchronize the time: ntpdate 0.europe.pool.ntp.org Original P ...

Retrieving feedback with Zend Framework 1

I'm struggling to come up with the right query to select all comments associated with a specific image and retrieve the authors of those comments. I want to formulate a query like this: select comment where comment_id == image_id && user_id(t ...

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

Using a JSON database to implement various user levels in a domain model

Here is the domain model that I believe to be accurate. I am currently attempting to implement this on a JSON database, but I am uncertain if I am headed in the right direction. From my understanding of JSON, there are no inherent relationships between obj ...

Dependencies in Angular

After diving into Angular recently, I've been grasping the concepts well. However, one thing that still puzzles me is dependency injection. I'm unsure whether it's necessary to declare all components of my application (services, controllers ...

The Isotope Error of Uncaught Type

I am currently in the process of developing a custom Wordpress theme and have been attempting to integrate Isotope into it using a tutorial I found online at this link. However, I've hit a roadblock with the jQuery portion of the tutorial. Upon check ...