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

255
Visualizações
echo json_encode has no response from server, but regular echo does?

I am trying to do a test request from my localhost, to a dev site I have just to test out some code. I am trying to make a very simple fetch request that simply just echos a response back in the form of json. This is cross site request and am disabling cors. The issues is, when I try to echo a response with echo json_encode the response says:
failed to load response data: No data found for resource with given identifier.
However, if I simply fire a regular echo 'a'; before the echo json_encode both responses now show up in the network tab. I am using Chrome. Here some code:

fetch('https://example.com/test.php',{
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        },
    mode: "no-cors",
    body:JSON.stringify({
        test:'1'
    })
})
.then(r => r.json())
.then(function(r){
    console.log(r)
})

In php I simply have, which returns nothing.

if(empty($_POST)){
    $_POST = json_decode(file_get_contents("php://input"), true);
}
echo json_encode(['200'=>'Got it']);

If I do:

echo 'x';
echo json_encode(['200'=>'Got it']);

My response looks like: (which the browser detects as proper json)

x{'200':'Got it'}

Do you have any ideas? I have tried putting any/all of these in my php file:

ini_set('display_errors', 1);
header("Cache-Control: no-cache, must-revalidate");
header("Content-type: application/json");
header("Access-Control-Allow-Origin: *");
json_last_error_msg();

Any ideas? thank you.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can echo out either an array or an object:

$obj = new stdClass();
$obj->message = 'gotit';
$obj->code = 200;
echo json_encode($obj); // prints {"message":"gotit","code":200}

$arr = Array('200' => 'gotit');
echo json_encode($arr); // prints {"200":"gotit"} 
about 4 years ago · Juan Pablo Isaza Relatório

0

see if this works

<?php
$content = trim(file_get_contents("php://input"));
echo json_encode(['200'=>'Got it']);
exit();
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