patrick
patrick

Reputation: 43

Can't display JSON on page

I have been trying to get my JSON code from a PHP file which is connected to my database to display on my website using an XMLHttpRequest, but we cant split them and display it.

We are using an php file example.php that does the following:

function jsonFromQuery($result) {
    if (mysql_num_rows($result) > 0) {
        while($r = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $json[] = $r;
        }
    } else {
        $json = "Table is empty";
    }

    return json_encode($json);
}

This will display the json code as following on the website if you open the php file:

[{"UserID":"2","Firstname":"Piet","Lastname":"Klaas","Age":"23","Specialization":"Voet","Branch":"Been","Interests":"Hoofd","Hospital":"OLVG","Email":"[email protected]","ProfilePicture":""}]

With this we use the following javascript file to request this php file and stringify and try and display it.

var request = new XMLHttpRequest;
request.open('GET' , 'http://myurl.nl/example.php', false);
request.send(null);

if (request.status == 0)
    console.log(request.responseText);

var obj = JSON.stringify(request);
var firstname = obj.Firstname;
document.writeln(firstname);`

But I get a massive string which includes the type status etc. And don't know how to split this up to display on their own. For example only Firstname = Piet on the page.

Upvotes: 0

Views: 91

Answers (2)

dpi
dpi

Reputation: 204

You are parsing the whole XMLHttpRequest object

var obj = JSON.parse(request);

try using just the response body

var obj = JSON.parse(request.responseText);

Upvotes: 0

Basic
Basic

Reputation: 26766

When you get the data back from PHP it's already in the form of a string. You need to use JSON.parse() to convert it into an object you can use. Try...

var obj = JSON.parse(request.responseText);
var firstname = obj[0].Firstname;
document.writeln(firstname);`

Note as well that the Json you're getting back is a list of objects: [{...},{...},{...}], so you can't just call .Firstname as you haven't specified which object you care about. Hence the [0] in the example above to pick out the first object.

One other thought... At present if your PHP doesn't find any results it's going to send back something that isn't in the format you're expecting. Consider either wrapping the list in an object with a status...

{
    "Success": true,
    "Results": [{...}, {...}]
}

Or make the PHP script return a different HTTP code to indicate failure (404 seems appropriate here)

For future reference, JSON.stringify does the opposite - it takes a complex object and converts it into Json

Upvotes: 2

Related Questions