$0.04

How to store and hold a value, that can stay the same or be changed on any browser by any user

Ask a question+
0

I am trying to make a webpage that will be able to store a variable, using JavaScript, called heart-count (I was trying it with jQuery and JSON, but didn’t have any luck, I could access the number easily, but I couldn’t change it).
This variable should be easily accessed by the JavaScript and be able to be changed (or in my case incremented).

The way that I have it right now is in a local file called heart.json inside this file is the following code:

{
    "hearts": 0,
    "heartLog": []
}

I am accessing that file in my JavaScript like this:

$.getJSON("../js/heart.json", function(data) {
    $("#num-hearts").text(data.hearts)
})

I was trying to use XMLHttpRequest (a way that was suggested to me):

var myJSON
$.getJSON("../js/heart.json", function(data) {
    myJSON = data
    setTimeout(() => {
        myJSON.hearts++
        console.log(myJSON)
        console.log(data)
    }, 2000);
})

var xhr = new XMLHttpRequest()
xhr.open("PUT","../js/heart.json",true)
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
xhr.send(JSON.stringify(myJSON))

I can’t confirm that this doesn’t work, since the way that the webpage is set up I test it using some interesting methods (interesting, but required…), and those use localhost. The reason I say that I can’t confirm that it doesn’t work, is because when I test the previous code, it says that “PUT” isn’t a valid protocol.

If there are any suggestions or validations of my code, that would help a lot.

add comment

0 Answer

Your Answer