/    Sign up×
Community /Pin to ProfileBookmark

Post JSON Array

I’m trying to post an array of ID’s via fetch then update a database.

Here’s what I have. When I console.log(IDs) I get an array of ID’s as expected.

But my respsonse is an empty array. Any ideas?

“`
const formData = new FormData();
formData.append(‘ID’, JSON.stringify(IDs));
fetch(‘savedata.php’,{
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: formData,
}).then(function (response) {
// The API call was successful!
return response.text();
}).then(function (html) {
console.log(html)
}).catch(function (err) {
console.warn(‘Something went wrong.’, err);
});
“`

my savedata.php page

“`
header(‘Content-Type: application/json’);
var_dump($_POST);
“`

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@sibertJan 17.2022 — I do this in a similar, but different way. No PHP. Only vanilla JS. Does this gives you any hint?

https://crud.go4webdev.org/api3create

https://jsfiddle.net/vkjxesu6/2/
Copy linkTweet thisAlerts:
@kiwisauthorJan 17.2022 — @sibert#1641602

The issue will be I'm needing it in PHP to save values into a database

It's also not in a form.
Copy linkTweet thisAlerts:
@sibertJan 17.2022 — > @kiwis80#1641612 It's also not in a form.

> const formData = new FormData();

> formData.append('ID', JSON.stringify(IDs));


I am not familiar with PHP, but does not this indicate that a form is used? Can you try with a JSON string instead?
Copy linkTweet thisAlerts:
@SempervivumJan 17.2022 — @kiwis80#1641600

There are two options to transmit your JSON data:

https://pastebin.com/hZe0uFEc
Copy linkTweet thisAlerts:
@ZorgJan 22.2022 — Change it to:

``<i>
</i>header('Content-Type: application/json');
echo json_encode($_POST);<i>
</i>
``
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.23,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...