i use a callback function into a object to update html (xmlhttprequest).
the firts time (onload), callback works fine. the second time (timer1) property url is undefined under the Post function no errors in console
my script and some console.log:
class PostJSON {
constructor() {
this.response = {};
this.url = "../iot/PostJSON.php";
}
callback = function() {
}
Post = function(datapost,callback) {
console.log(this.url);
console.log(datapost);
let xhttp = new XMLHttpRequest();
let myJSON = JSON.stringify(datapost);
xhttp.open("POST", this.url, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(myJSON);
var instance = this;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let json = JSON.parse(this.responseText);
instance.response = json;
instance.callback();
}
}
}
}```
const net = new PostJSON();
net.callback = function(){
console.log(this.response["data"]["datetime"][0]);
document.getElementById("temp").innerHTML = this.response["data"]["temp"][0] + "°C";
}
window.addEventListener('DOMContentLoaded', net.Post({"id":1}) );
var myTimer1 = setInterval(net.Post, 5000,{"x":1,"id":1});