/    Sign up×
Community /Pin to ProfileBookmark

Async / await fetch – Posting JSON data

Good evening all.

I was hoping someone might be able to help me. I am fairly competent with JS and PHP but not so much with the fetch API which I am currently trying to get my head around.

The issue is this. If I use the .then syntaxt to handle the promises everything works fine, however if I create an async function and use the await syntax, my data is being posted to my server side script as text, not JSON, even though the headers are set correctly. Therefore, my response back from my server side script is garbage because it’s expecting JSON to be sent to it. If I adjust my server side PHP script to accept text, eveything works as it should. I could change it to handle text but I would love to know what I’m doing wrong. Code is below:

### Client Side JS

` async function getDbResult(id) {
const result = await fetch(‘/shop_common/db_query.php’, {
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’
},
body: JSON.stringify(id),
});
const jsondata = await result.json();
return jsondata;
} `

### Server Side PHP

When I pass data to this script using the async/await syntax, $product_id is null because it’s text not JSON.

`<?php
//Obtain the product_id from the JSON data via the php input stream
$json = file_get_contents(‘php://input’);
$data = json_decode($json);
//Extract the value of ‘product id’ from the decoded JSON stream
$product_id = $data->product_id;
//Set the credentials for accessing the Db
$db_host = “**********************”;
$db_user = “**********************”;
$db_pass = “**********************”;
$db = “**********************”;
$db_table = “**********************”;
$connect = mysqli_connect($db_host, $db_user, $db_pass, $db);
if ($connect -> connect_error) {
echo “Failed to connect to DB: ” . $connect -> connect_error;
exit();
}
//Select all columns from the table where the product id matches the row
$sql = mysqli_query($connect, “SELECT * FROM $db_table WHERE product_id='”.$product_id.”‘”);
$result = mysqli_fetch_all($sql, MYSQLI_ASSOC);
exit (json_encode($result));
?>`

Any help very graciously received!

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogMay 17.2021 — Maybe just add to the PHP before anything gets output:
[code=php]
header('Content-Type: application/json');
[/code]
×

Success!

Help @andyc829 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 5.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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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