JS Game Text not showing

Hello!
So I made a game in js and html.
Here is some code:

var jsonFile = “”
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(xhttp.responseText)); //this works, and prints 138
var jsonFile = JSON.parse(xhttp.responseText)

}

};
xhttp.open(“GET”, “/checkUserScore?username=” + username + “?password=” + password, true);
xhttp.send();

Then I have:

document.getElementById(“playerScore”).innerHTML = "Coins: " + jsonFile

But on the page, it always says "Coins: " And just a blank space!
Could anyone help? It should say “Coins 138” in this case!

1 Like

Can you open the dev console and see if there are any errors?

There are no errors @RiversideRocks

1 Like

Odd. Maybe remove this line? It could be confusing the program because jsonFile is defined twice.

1 Like

hmm well then varJson file is not defined

1 Like

Might be your issue there.

Also, you should add a semicolon to the end of here:

1 Like

Hi Losh531,

You need to make use of the jsonFile inside the callback, like this:


var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(JSON.parse(xhttp.responseText)); //this works, and prints 138
    var jsonFile = JSON.parse(xhttp.responseText)
	document.getElementById(“playerScore”).innerHTML = "Coins: " + jsonFile
  }
};

xhttp.open(“GET”, “/checkUserScore?username=” + username + “?password=” + password, true);
xhttp.send();

If you try to use it outside the callback, it hasn’t got a value yet. It’s only when the callback function is called that the value is set to something other than blank.

Hope it helps :slight_smile:

3 Likes

@SteGriff Good idea, but I need to do this:

document.getElementById(“playerScore”).innerHTML = "Coins: " + jsonFile

Every second on repeat out of the callback!

1 Like

Why did you used unicode quotes? It may confuse some newbies.

@Losh531 You can add the line inside the event callback as well as inside the setInterval / timer.

1 Like

The curly quotes were in OP’s original that I copied+pasted. I guess they were inserted by a fancy editor at some point.

1 Like