1

Essentially, I need to create an array of arrays.

I am using Javascript inside an .HTML file. I am reading from a .txt file

Let's call the first array "alerts" and then each array inside that is an "incident."

Each incident has three values associated with it: an ID number, a latitude value, and a longitude value.

If I put the values in a text file and each one is on a separate line, what function/how should I go about reading in each, and then assigning them to variables to be stored in an incident array?

<script type="text/javascript">

        //open text file
        $f = fopen("LatLngTest.txt", "r");
        //read line by line: 1st line=ID, 2nd line=LAT, 3rd line=LNG

        //store in ID, LAT, LNG variables

        //close text file
        fclose($f);
        //create incident array and save ID, LAT, LNG as one incident
        var incident = new Array (ID, LAT, LNG);

        //create array of alerts
        var alerts = new Array();
        //if statement to check length of array 

            //and add this incident to the end
            //alerts[i] = incident;
    </script>
9
  • 2
    You have PHP in your Javascript. You can't do that. Commented Feb 28, 2014 at 21:34
  • Are you running the Javascript in a browser, or on the server using Node.js? Commented Feb 28, 2014 at 21:35
  • @Barmar I'm still a novice with this language, could you elaborate or make a suggestion on what to replace it with? Commented Feb 28, 2014 at 21:36
  • And where is the text file? If it's on the server, Javascript can't read it, you need to use a server script. Commented Feb 28, 2014 at 21:37
  • Do you want to read file text using javascript ?? Commented Feb 28, 2014 at 21:37

1 Answer 1

1

You need to give the page the text before you send it to the server, or use AJAX. I'm going to assume the easiest for you will be just dumping it onto the page:

<script>
  (function(){
    <?php echo "var fileContent = '" . file_get_contents("LatLngTest.txt") . "'," ; ?>
    alerts = fileContent.split("\n").map(function(lineItem){
       // Assuming each line is csv: ID,LAT,LNG 
       // and that there are no commas in the values
       var field = lineItem.split(",");
       return {ID: field[0], LAT: field[1], LNG: fields[2]};
    });

    // now alerts looks like this: [{ID: ..., LAT: ..., LNG: ...}, {...}];

  })();
</script>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.