Search code examples
javascriptjqueryjsonxmlhttprequest

Making a local file hold a value to use by any user


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.


Solution

  • How ya doin? I'm sorry to say but you can not write to a file in server directly with jQuery or Javascript because Javascript is frontend language. It doesn't have the capability to do so.

    However you can send or receive data with XMLHttpRequest, but you need a server side language/program to process your XMLHttpRequest.