0

I sent JSON object from PHP to JS, and in HTML I get the answer "undefined". Why?

PHP file server.php

$filename = "osoba.json";
$file = file_get_contents($filename);
$json_decoded = json_decode($file);
$json_encoded = json_encode($json_decoded);
echo $json_encoded;

JS file script.js

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200){
        var mojNiz = JSON.parse(xhr.responseText);
        document.getElementById("demo").innerHTML = mojNiz.ime;
    }
};

xhr.open("GET", "server.php", true);
xhr.send();

and HTML index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Pocetna stranica</title

</head>
<body>
    <p id="demo">

    </p>
    <script type="text/javascript" src="script.js"></script>

</body>
</html>

also have a JSON string osoba.json

{"zaposleni":[{"ime":"Dunjica","prezime":"Markovic"},{"ime":"Jovan","prezime":"Markovic"},{"ime":"Marija","prezime":"Markovic"}]}
DanijelS
  • 3
  • 1
  • Is there a reason for you to first decode and then encode the file in php before you send it? Is there a reason you use XMLHttpRequest instead of fetch? – some Jan 26 '20 at 12:13
  • 1
    You get `undefined` because the top-level object defined by that JSON doesn't have an `ime` property. It has a `zaposleni` property that refers to an array of objects, and those objects have `ime` properties, but not the top-level object. – T.J. Crowder Jan 26 '20 at 12:14
  • In the PHP code, why parse the JSON from the file, then re-stringify it? Do you want to ensure it's valid before sending it, or...? – T.J. Crowder Jan 26 '20 at 12:14
  • Yes, I want to ensure, no special reason, but it's not working eatherway... – DanijelS Jan 26 '20 at 12:22
  • I deleted a "zaposleni" from .json file, and still get "undefined" – DanijelS Jan 26 '20 at 12:26
  • Could you `console.log(mojNiz)`, look in the console and show us what data you receive. – Emiel Zuurbier Jan 26 '20 at 12:28
  • I get this message "script.js:18 Uncaught ReferenceError: mojNiz is not defined at script.js:18" – DanijelS Jan 26 '20 at 12:29
  • @T.J.Crowder My friend, "How can I access and process nested objects, arrays or JSON?)" this still doesn't resolve my problem. I try another code in .php file, and everything and still not working... – DanijelS Jan 26 '20 at 12:58
  • @DanijelS - Read the answers there carefully. The issue is that you're not using the correct code to access the data. The answers there describe how to access data in various object structures. For one thing, there are multiple `ime` properties, not just one. In the JSON quoted in the question, for instance, once you parse it you'd access the **first** `ime` property via `mojNiz.zaposleni[0].ime`. But more likely, you want a look. – T.J. Crowder Jan 26 '20 at 13:02
  • 1
    @T.J.Crowder Thank you, I understand it now. Thanks – DanijelS Jan 26 '20 at 13:12

0 Answers0