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

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

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 Denunciar

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 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