Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

277
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda