0

I have an html file with just a table, containing 5 cells in a single row, displaying 5 NFL teams. The td's ids are "Team0" to "Team4" (left to right).
My purpose is to move a double clicked team to the last position in the right (to the cell wich id is "Team4").
In every td I have a call to Rearrange_Teams(iPosition).
iPosition is the number in the td id (Team3 calls Rearrange_Teams(3).

The following code works fine, but I'd like to change the function Load_Teams(), in order to load the teams from a file in my desktop (where my html file is saved):

<script>
    Array.prototype.Rearrange = function(from,to){
        this.splice(to,0,this.splice(from,1)[0]);
        return this;
    };

    var aTeams = [];
    Load_Teams();
    List_Teams();

    function Load_Teams() {
        aTeams [0] = "PANTHERS";
        aTeams [1] = "CARDINALS";
        aTeams [2] = "BENGALS";
        aTeams [3] = "BRONCOS";
        aTeams [4] = "PATRIOTS";
    }

    function List_Teams() {
        document.getElementById("Team0").innerHTML = aTeams [0];
        document.getElementById("Team1").innerHTML = aTeams [1];
        document.getElementById("Team2").innerHTML = aTeams [2];
        document.getElementById("Team3").innerHTML = aTeams [3];
        document.getElementById("Team4").innerHTML = aTeams [4];
    }

    function Rearrange_Teams(iPosition_Clicked) {
        aTeams.Rearrange(iPosition_Clicked,4);
        List_Teams();
    }
</script>

Both the html page and the data file (JSON? txt?) are supposed to be saved in my computer (desktop or user directory, whatever...). I just can't find an answer to help me with this... well, at least I can't understand the changes I'd have to make in the codes I've seen around...

The idea is to save the changes in the list, so I have to load the previous configuration and save the actual ones...
It's not possible to set up a local webserver, as I was suggested before, cause the intention is to use this page at my work and the users don't have administrator privileges (myself included).
We currently use an Excel worksheet with VBA, to get the job done, but I want to change it to the browser.

EDITED AFTER REPLY:
I've tried:

function Load_Teams() {
    var actual_JSON;
    loadJSON("My_File_with_Data.json", function(response) {
        actual_JSON = JSON.parse(response);
    });
    alert(actual_JSON);
}

function loadJSON(filename, callback) {   
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', filename, true);
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
        }
    };
    xobj.send(null);  
}

But nothing happened... The alert(actual_JSON) shows nothing (just a blank pop up, with an "ok"). And I have no idea how I should pass the content of actual_JSON (does it really have any???) to aTeams.
The file My_File_with_Data.json looks like this:

{"jTeams": ["PANTHERS","CARDINALS", "BENGALS", "BRONCOS", "PATRIOTS"]}

NEW APPROACH:

    var aTeam = [];
    readTextFile();
    List_Teams();

    function readTextFile(){
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", "Teams.txt", true);
        rawFile.onreadystatechange = function (){
            if(rawFile.readyState === 4){
                var  allText = rawFile.responseText;
                aTeam = allText.split("/");
                alert(aTeam[4]);
            }
        }
        rawFile.send();
    }

    function List_Teams() {
        document.getElementById("Team0").innerHTML = aTeam[0];
        document.getElementById("Team1").innerHTML = aTeam[1];
        document.getElementById("Team2").innerHTML = aTeam[2];
        document.getElementById("Team3").innerHTML = aTeam[3];
        document.getElementById("Team4").innerHTML = aTeam[4];
    }

The file Teams.txt looks like: PANTHERS/CARDINALS/BENGALS/BRONCOS/PATRIOTS

When readTextFile() runs, the alert(aTeam[4]) displays PATRIOTS. But List_Teams() fills my table with undefined.
How come??? Seems to be a matter of scope, but aTeam is a global!...

RGeral
  • 13
  • 6
  • perhaps this could help you https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript –  Dec 11 '16 at 17:10
  • 2
    loading JSON from a local file is going to cause you problems in some browsers. You're better of just setting up a local webserver and making an endpoint that serves up the file. – Michael Paccione Dec 11 '16 at 19:17
  • @DaemonOfTheWest I've seen that page before, but couldn't make it work... what is that **"response"** in **JSON.parse(response)**? – RGeral Dec 11 '16 at 21:07
  • @RGeral `response` is what is passed back into the callback function by the `loadJSON function` - in this case, it is the response from the attempt to access your file. If successful, `response` becomes your file. By using `JSON.parse()`, they are converting the result into a friendly format for use with javascript. –  Dec 11 '16 at 21:19
  • @MichaelPaccione I'm not sure about the implications of what you've suggested, but I think I couldn't do it cause the html page is supposed to be viewed in a machine at my work place. At this time I achieve my goal using Excel and VBA, but I wanna try to make this work with just a browser... – RGeral Dec 11 '16 at 21:19
  • Possibly. Also be aware that the xhr property (response or responseText) depends on the responseType. A man could just add a dynamical script tag if it is called on local machine with the json added to a variable. – Lain Dec 11 '16 at 21:22
  • @RGeral looking at your example of what you tried, I don't see you calling `init()` anywhere. I will post an answer that should hopefully explain it more. –  Dec 11 '16 at 21:22
  • @DaemonOfTheWest my mistake... for a moment I thought that **response** should have a value in **loadJSON(function(response)**..... but it will be assigned later. OK. Anyway... couldn't make it work... – RGeral Dec 11 '16 at 21:24
  • @RGeral when opening your developer console do you get any error messages? –  Dec 11 '16 at 21:29
  • By the way, does my **JSON file** looks ok? I'm not sure about it. At this point I'm trying to learn how to load five strings, but soon after I'll have to save data to **My_File_with_Data.json**, and it won't be just five strings... later. – RGeral Dec 11 '16 at 21:32
  • @DaemonOfTheWest wow!... I wan't seeing the developer console. It's saying: VM43 Control List.html:49 XMLHttpRequest cannot load file:///C:/Users/*****/Desktop/My_File_with_Data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. – RGeral Dec 11 '16 at 21:37
  • @RGeral Welp... apparently you can't directly load from your local disk without setting up a local server at that location. –  Dec 11 '16 at 21:40
  • Firefox says: SyntaxError: JSON.parse: expected ':' after property name in object at line 3 column 7 of the JSON data – RGeral Dec 11 '16 at 21:41
  • @RGeral your JSON is a bit off. "AAA","BBB","CCC" etc should be contained inside an array: `{"jTeams": ["AAA", "BBB", "CCC", "DDD", "EEE"] }` –  Dec 11 '16 at 21:43
  • @DaemonOfTheWest first time something happened here. The element **Team[0]** now displays **undefined**. That happened after I put those brackets... – RGeral Dec 11 '16 at 21:47
  • @RGeral you may need to convert the JSON results into a JS array first. –  Dec 11 '16 at 23:27
  • I said it's easier to use a file server because to properly access a file locally you would have to use the Filereader API in the browser. Directly calling a local file is a security issue and will be blocked in Chrome. https://developer.mozilla.org/en-US/docs/Web/API/FileReader – Michael Paccione Dec 11 '16 at 23:53
  • "It's not possible to set up a local webserver, as I was suggested before, cause the intention is to use this page at my work and the users don't have administrator privileges (myself included). We currently use an Excel worksheet with VBA, to get the job done, but I want to change it to the browser." — Security restrictions in browsers makes this impossible then. – Quentin Dec 16 '16 at 07:00
  • @Quentin but I get no error message... (control + shift + J) – RGeral Dec 16 '16 at 07:03

1 Answers1

0

A slightly modified version of code from this blog post, here is a function you can use to load JSON:

function loadJSON(filename, callback) {   
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', filename, true);
  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
      // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
      callback(xobj.responseText);
    }
  };
  xobj.send(null);  
}

to use this function, you need a callback:

var actual_JSON;
loadJSON("localhost:8000/my-file", function(response) {
  // Parse JSON string into object
  actual_JSON = JSON.parse(response);
});
alert(actual_JSON);

replace /my-file with a path to your file.

You also need a server at the location, which you can set up quickly like this

Community
  • 1
  • 1