Search code examples
javascriptjsonxmlhttprequestgetjson

Reading data from JSON and display in html


I want to read and display data from an external JSON file and display it using HTML.

What I have so far:

Javascript:

var xmlhttpRoles = new XMLHttpRequest();
var urlRoles = "../portal/getResults.php";

xmlhttpRoles.onreadystatechange = function() {
    if (xmlhttpRoles.readyState == 4 && xmlhttpRoles.status == 200) {
        var rolesArray = JSON.parse(xmlhttpRoles.responseText);
        functionRoles(rolesArray);
    }
};
xmlhttpRoles.open("GET", urlRoles, true);
xmlhttpRoles.send();

function functionRoles(arr) {
    var out = "";
    var i;
    alert(arr);
    for(i = 0; i < arr.length; i++) {
        out += '<p>' + arr.results[i].Title +'</p>';
    }
    document.getElementById("id02").innerHTML = out;
}

getResults.php file output:

{

"results": [
    {
        "DocId": 2204,
        "Title": "Lorem ipsum dolor sit amet, consectetur",
        "Locations": [
            {
                "State": "New York",
                "City": ""
            },
            {
                "State": "New York",
                "City": "New York City"
            }
        ],
        "Topics": [
            3,
            7,
            11
        ],
        "PublicationYear": "2011",
        "Organization": "New  Yorks Times",
        "WebLocation": "www.google.com",
        "Description": "Lorem Ipsum"
    }
],
"TotalMatches": 1

}

HTML:

<div id="id02"></div>

I have been trying to get the value of title or any other element for that matter and have been unsuccessful. I'm not sure what I'm doing wrong.


Solution

  • The JSON is an object and objects has no length property. I think that you need to change the for condition:

    for(i = 0; i < arr.results.length; i++) {
        out += '<p>' + arr.results[i].Title +'</p>';
    }