R.Cairns R.Cairns - 24 days ago 14
PHP Question

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;

Answer

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 an event listener to the ajax object:

ajax.addEventListener("load", loadCompleted);  

then create a function to handle the result:

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

Full example:

var url = 'https://jsonplaceholder.typicode.com/posts/1';

var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.responseType = 'json';
ajax.send();
ajax.addEventListener("load", loadCompleted);  

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

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

Comments