/    Sign up×
Community /Pin to ProfileBookmark

Get POSTED fetch data

I’m having trouble posting a form using fetch.

Here’s my code, when I get to my PHP code I can’t find any of the posted form values

Here’s my JS code.

I don’t get any JS errors and it returns static information from my destination. I just can’t return or error log any posted data.

“`
const registerForm = document.getElementById(“registerForm”);
registerForm.addEventListener(“submit”, handleFormSubmit);

async function handleFormSubmit(event) {
event.preventDefault();

const form = event.currentTarget;
const url = “functions/validateUser.php”;

try {
const formData = new FormData(form);
console.log(formData);
const data = await postFormDataAsJson({ url, formData });

console.log(data);
} catch (error) {
console.error(error);
}
}

async function postFormDataAsJson({ url, formData }) {
const plainFormData = Object.fromEntries(formData.entries());
const formDataJsonString = JSON.stringify(plainFormData);

const fetchOptions = {
method: “POST”,
headers: {
“Content-Type”: “application/json”,
Accept: “application/json”,
},
body: formDataJsonString,
};

const response = await fetch(url, fetchOptions);

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}

return response.json();
}
“`

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumFeb 07.2021 — When transmitting parameters this way they will be available in the PHP by this code:

`$params = json_decode(file_get_contents("php://input"));`

Your code is an overkill of complexity. Try it like this instead:
const params = {
par1: 'some-param',
par2: 'some-other-param',
par3: [1, 2, 3, 4, 5]
};
fetch('fetch-api-json-request.php', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(res => {
return res.text();
}).then(res => {
console.log(res);
});
Copy linkTweet thisAlerts:
@VITSUSAFeb 08.2021 — @kiwis80#1627694 Can you please share the "error message" with us? It will help to understand the exact problem.
Copy linkTweet thisAlerts:
@SempervivumFeb 08.2021 — @VITSUSA#1627713 The TO wrote:
>I don't get any JS errors
Copy linkTweet thisAlerts:
@kiwisauthorFeb 09.2021 — @Sempervivum#1627696

How do I pass in my form values?

Is it as simple as this?

``<i>
</i> const params = {
username: documnet.getElementById("username").value,
par2: 'some-other-param',
par3: [1, 2, 3, 4, 5]
};<i>
</i>
``
Copy linkTweet thisAlerts:
@SempervivumFeb 09.2021 — @kiwis80#1627735 Yes, you can prepare the parameters this way. However when there is a form, it's much easier to use formdata like this:
&lt;form&gt;
&lt;input type="text" name="param1" value="some-param"&gt;
&lt;input type="text" name="param2" value="some-other-param"&gt;
&lt;input type="number" name="numparam" value="1.24"&gt;
&lt;/form&gt;
&lt;span id="out"&gt;&lt;/span&gt;
&lt;script&gt;
fetch('testpost.php', {
method: 'post',
body: new FormData(document.querySelector('form'))
}).then(res =&gt; {
return res.text();
}).then(res =&gt; {
console.log(res);
document.getElementById('out').innerHTML = res;
});
&lt;/script&gt;
The parameters are available as $_POST then. IMO when there is a form there is no benefit in using JSON as there is no nesting in the parameters.

Edit: If you prefer to stick to json you can convert the formdata to json as described here:

https://stackoverflow.com/questions/41431322/how-to-convert-formdata-html5-object-to-json
×

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.19,
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,
)...