1

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
1
  • 2
    Check the PHP file first in your browser, to see if it does indeed return JSON. Commented Nov 26, 2022 at 18:23

1 Answer 1

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

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.".
@KIKOSoftware you are right. English is not my first language. I try to do my best. Your choice of words is better.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.