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

254
Views
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 answers
Answer question

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 Report

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