Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Async / await fetch - Posting JSON data

andyc829

New Coder
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:


[CODE lang="javascript" title="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;
}[/CODE]

[CODE title="Server Side Code" highlight="5,8"]<?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));
?>[/CODE]

When I pass data to the server side script using the async/await syntax, $product_id is null because it's receiving text instead of JSON.

Any help would be greatly appreciated :)
 
An async function needs to return a Promise. You are returning the result of an await, which is not a Promise but an unwrapped value. You should simply return result.json() so that the method returns a Promise. You will then need to call the function in .then style or call it from another async function (which would again need to return a Promise.)

That should fix it, I hope. I'm not too experienced with PHP but I am fairly sure the issue is on the clientside.
 
The response object, returned by the await fetch(), is a generic placeholder for multiple data formats.

For example, you can extract the JSON object from a fetch response:

async function fetchMoviesJSON() {
const response = await fetch('/movies');
const movies = await response.json(); return movies;
}

fetchMoviesJSON().then(movies => {
movies; // fetched movies
});

response.json() is a method on the Response object that lets you extract a JSON object from the response. The method returns a promise, so you have to wait for the JSON: await response.json().

The Response object offers a lot of useful methods (all returning promises):

  • response.json() returns a promise resolved to a JSON object
  • response.text() returns a promise resolved to raw text
  • response.formData() returns a promise resolved to FormData
  • response.blob() returns a promise resolved to a Blob (a file-like object of raw data)
  • response.arrayBuffer()() returns a promise resolved to an ArryBuffer (raw generic binary data)
 
Hello simpleauthority and Steveskok.

It turns out I was being really stupid. I wasn't formatting the input data correctly before stringifying it.

I am developing an ecommerce app and the client side code function takes the argument 'id'. I didn't concatenate it with the index name. For example:

json_data = {"Product_id": id}

Thanks for your help guys!
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom