0

Just a small disclaimer: I only have basic knowledge of JS and I'm just starting to learn it, so my code might be really stupid.

I want to take the contents of a .JSON file and assign every entry to a separate JS variable. I am running a local server to be able to read the files as (if I understood this correctly) Chrome would prevent me from accessing local files due to their policy.

Here's the JSON file contents:

{
    "current" : "current_value",
    "voltage" : "current_voltage"
}

And here's my JS script (again this is 100% dumb code as I'm just starting out)

<script src="/jquery-3.5.1.min.js"></script>
<script>
    var data = $.getJSON("localhost:8888/data.json", function(json){
        console.log(json);
        var current = json.current;
    });
    alert(current);
</script>

Here's the File Structure:

L main.html
L jquery-3.5.1.min.js
L data.json

What I want to do is to take the value of current in the .JSON file and assign it to the current JS variable. Basically this would be used to have a local web interface to check the real time voltage and current of a battery.

Thank you for taking your time to read this,
Huky

Hukify
  • 161
  • 1
  • 2
  • 7
  • 1
    Your AJAX code is almost correct. The issue is because the request is asynchronous. As such you cannot work with any of the values in the response until the AJAX request is complete. To do this you need to place ***all*** code reliant on the response within the AJAX callback - as you've done for the `var current = ...` line. Everything that relies on the `current` variable also needs to be within this scope, or defined in a function which is invoked from that scope. I've marked a couple of duplicates which cover the topic of working with async code very well, hopefully they are useful. – Rory McCrossan Feb 06 '21 at 17:06
  • @RoryMcCrossan so do I just need to move the `alert(current);` line into the curly brackets of the `function(json){}` ? Just tried that and it still doesn't work. Or am I wrong again? – Hukify Feb 06 '21 at 17:17
  • Basically, yes that will work. If it didn't then then may be a problem with your ajax request – Rory McCrossan Feb 06 '21 at 17:18
  • Oh I got it, instead of referencing `"localhost:888/data.json"` I just needed to type `"/data.json"`. Thank you so much for your help, it cleared everything up a bit! – Hukify Feb 06 '21 at 17:22
  • @RoryMcCrossan So now I have another issue, the json file is going to be updated a lot and it seems like even when I updated the .JSON, the alert still says `value1` instead of the new value. It takes a lot of time before it updates. – Hukify Feb 06 '21 at 17:25
  • In that case you need to disable caching, either on the server side or in the ajax request. – Rory McCrossan Feb 06 '21 at 19:39

0 Answers0