Search code examples
javascriptarraysajaxxmlhttprequestactivexobject

Displaying a line or a value from a CSV using Javascript/AJAX


The CSV file looks like this:

STATION,DATE,HLY-WIND-AVGSPD,HLY-WIND-VCTDIR
USW00013904,01-01T01:00:00,5.6,350
USW00013904,01-01T02:00:00,5.4,346
USW00013904,01-01T03:00:00,5.5,342
USW00013904,01-01T04:00:00,5.5,349
USW00013904,01-01T05:00:00,5.5,348

I am not very well acquainted with Javascript yet. I want the window.alert below to display a value from the CSV. The script does pull the CSV and the textarea displays it. Currently, the alert would display the letter "S". But I would want it to display the name "STATION". I would also like to know how to display values from other lines, as in putting windValue.value[0,1] in the alert would display "USW00013904".

Can, I use the comma separator and pull the values based on their location using any basic javascript commands?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javascript-only file reading </title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body onload="doLoad('')">

<textarea cols="50" rows="40" id='windValue'></textarea>

<script type='text/javascript'>
// https://www.webdeveloper.com/forum/d/242887-read-server-csv-file-into-javascript-array/6
function el(tid)
{
  return document.getElementById(tid);
}

function IO(U, V) {//LA MOD String Version. A tiny ajax library by Dan Davis.
    var X = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
    X.open(V ? 'PUT' : 'GET', U, false );
    X.setRequestHeader('Content-Type', 'csv')
    X.send(V ? V : '');
    return X.responseText;
}

function doLoad(){
  el("windValue").value = IO("data/austinairport.csv");
}

  window.alert(windValue.value[0]);
</script>
</body>
</html>

Solution

  • I solved this. You can search through the output as an array if you use the following code:

    window.alert(windValue.value.split(/\s+/)[1].split(",")[3]);
    

    The code above will return the result: "350" as a string.

    window.alert(parseInt(windValue.value.split(/\s+/)[1].split(",")[3]));
    

    The code above will return the result: 350 as an integer.