Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

275
Views
Can't display JSON code in php when send threw fetch() in Javascript

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;
?>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!