Home > Net >  Can't display JSON code in php when send threw fetch() in Javascript
Can't display JSON code in php when send threw fetch() in Javascript

Time:12-17

I have tried to echo my json into my html page with php, but it only prints in console or gives back an error. I'm pretty new to this so please help.

this is the javascript with fetch and activated onclick to submit one to php

async function hey(){
let click = 1;

await fetch('data.php',{
    method: 'POST',
    header: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(click),
}).then(response => response.json())
.then(data => {
  console.log(data);
})
.catch((error) => {
  console.error(error);
});}

this is the php but it will only ever print to the console

<?php
$json = file_get_contents('php://input');

echo $json;
?>

CodePudding user response:

let's decripte what you were doing:

first thing first, the way you are calling your method:

async function hey(){
  let click = 1;

  await fetch('data.php',{
    ...
}

if you want to return the value of the json through your function, well you have to return it. I think you are expected to get it from the method, so you cound change to:

async function hey(){
  let click = 1;

  return await fetch('data.php',{
    ...
}

like this your function is actually returning something. If you expected it from returning through the invocation from then(), it won't work, it is one scope deeper.

I think the fetch part is ok, so I jump directly to the then() part, that actually looks like :

.then(response => response.json())
.then(data => {
  console.log(data);
 ....

I believe that you don't need 2 call to the then() method here. You could simply do:

 then(response => return response.json())

I didn't try it, but i don't think you need to call the json method, because you are already sending a json. But to do that you would need to include in php the headers needed to precise it, because php doesnt know you are sending a json and will probably do something else. So your php script should looks like:

<?php
header('Content-Type: application/json; charset=utf-8');
$json = file_get_contents('php://input');

echo $json;

cheers

  • Related