David98761324
David98761324

Reputation: 43

Can't parse json from php into javascript

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.

Upvotes: 1

Views: 131

Answers (1)

FarrisFahad
FarrisFahad

Reputation: 372

You need to run php on a local server. PHP cannot be run anywhere on your document. You need to install xampp or apache.

Upvotes: 1

Related Questions