Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

274
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda