Search code examples
phpjsonxmlxmlhttprequestnosql

Parsing string to json/XML from a HttpRequest


I'm trying to parse a string from a noSQL database. With difficulty. when you access the PHP file it gives a result like this:

[{"timestamp":"2016-11-07T09:48:30.335Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:29.015Z","Id":"d7ee735f16b5"},    
{"timestamp":"2016-11-07T09:48:27.688Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:27.085Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:26.577Z","Id":"d7ee735f16b5"}]

The same result is given in the network of the console.

When I then attempt to stringify the response it shows null.

Please can anyone help me access the timestamp values. Here is the current code:

var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.responseType = 'json';
ajax.send();
var jsonResponse = JSON.stringify(ajax.response);
document.getElementById('demo').innerHTML = jsonResponse;

Solution

  • Most likely the response hasn't returned from the server yet in this example. Also verify that an element with an id of 'demo' does in fact exist in your html document.

    Add event listeners to the ajax object:

    ajax.onload = loadCompleted;  
    ajax.onerror = onLoadError;
    

    then create a function to handle the result:

    var jsonResponse = JSON.stringify(ajax.response);
    document.getElementById('demo').innerHTML = jsonResponse;
    

    Full example (updated per Bozidar's comments):

    var url = 'https://jsonplaceholder.typicode.com/posts/1';
    
    function loadCompleted() {
        console.log(ajax.response)
        var jsonResponse = JSON.stringify(ajax.response);
        document.getElementById('demo').innerHTML = jsonResponse;
    }
    
    function onLoadError() {
        //handle error logic
    }
    
    var ajax = new XMLHttpRequest();   
    ajax.onload = loadCompleted;
    ajax.onerror = onLoadError;
    ajax.open("GET", url, true);
    ajax.responseType = 'json';
    ajax.send();
    

    See https://jsfiddle.net/px3mxa4n/ for a working example.