Just started learning JS and, I'm using W3schools to learn, so i get to the JSON PHP section and it comes this example:
JS Code
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "/php/demo_file.php");
xmlhttp.send();
demo_file.php
<?php
$myObj = new stdClass();
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>
I get this error:
Error
Like I said, I'm just learning and this seems like a trivial problem, the demo is working on the w3schools website but not working on my editor.
disinfor
11.6k2 gold badges37 silver badges49 bronze badges
asked Nov 26, 2022 at 18:18
-
2Check the PHP file first in your browser, to see if it does indeed return JSON.KIKO Software– KIKO Software2022年11月26日 18:23:47 +00:00Commented Nov 26, 2022 at 18:23
1 Answer 1
You need to run php on a local server. PHP cannot be run anywhere on your document. You need to install xampp or apache.
answered Nov 26, 2022 at 18:42
2 Comments
KIKO Software
I think you have the right idea, but you're not expressing it very well. "PHP cannot be run anywhere on your document.", don't you mean: "A PHP script does not execute in the browser, like Javascript, it needs a webserver with a PHP interpreter. Running a PHP script directly from your computer will not work.".
FarrisFahad
@KIKOSoftware you are right. English is not my first language. I try to do my best. Your choice of words is better.
default