0

I'm making a very simple web UI for a CSV file with the results of a python crawler. The UI needs to display the contents of each row individually in different div tags. The row needs to be selected at random after the user presses a button. this will then display the data selected from the CSV file.

I'm very new to JavaScript although i have some experience with other programming languages.

the code i currently have is as follows:

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery-1.12.3.min.js" type="text/javascript">
</script>
<title>Untitled Document</title>
<style type="text/css">
body { font-family:arial, helvetica, sans-serif; font-weight:normal; font-size:13px; color:#000; text-align:left; margin:3px 0px; }
#wrap { width:500px; height:500px; margin:20px;  }
</style>
</head>

<body>

<button onclick="myFunction()">Click me</button>

<div id="wrap" style="background-color:#666; height:100%; width:100%">
</div><!-- end wrap -->

<script type="text/javascript">
 $.get('testResults.csv', function myFunction(data) {
    var build = '<table border="1" cellpadding="2" cellspacing="0" style="border-collapse: collapse" width="100%">\n';
    var rows = data.split("\n");
    rows.forEach( function getvalues(thisRow) {
    build += "<tr>\n";
    var columns = thisRow.split(",");
    for(var i=0;i<columns.length;i++){ build += "<td>" + columns[i] + "</td>\n"; }
    })
    build += "</table>";
    $('#wrap').append(build);
 });
</script>

</body>
</html> 

I found this particular block of code on the net, and havent been able to get it to output a single row as opposed to the entire CSV file as a table.

Preferably the button (which doesn't work) would run the code parsing each value in the row to an id or class that i can pick up in the HTML(outputting as a table is not needed). as far as specifying certain values, I can write some if statements for that another time.

CSV file here: http://www.filedropper.com/testresults

thanks!

gezer4000
  • 103
  • 1
  • 9

1 Answers1

2

Conceptually you are on the right path, the largest issues were:

  1. You needed a handler defined named myFunction
  2. You probably did not want the myFunction function name in your $.get()

This demo uses reduce() as I am keen on it rather than building a string via forEach() but your original strategy is not wrong.

Originally, this demo fetched the csv every time the button was clicked then selected a random row to display. I refactored this a bit to support fetching the remote data only once.

// ============================
// Allow for a cached result
// ============================
var csvRows = [];
// ============================

// ============================
// Given an array of rows build a table.
// ============================
function buildTable(csvRows){
  // Our base result
  var $table = $("<table cellpadding=\"2\" cellspacing=\"0\"></table>");

  // ============================
  // For each row in the CSV build a <tr /> and append it to the <table />
  // ============================
  $table = csvRows.reduce(function($table, csvRow){

    // For this demo just take the first few cells/columns
    var csvRowCells = csvRow.split(",").slice(0, 4);

    // Our base table row
    var $tr = $("<tr>/tr>");

    // ============================
    // For each cell row build a <td /> and append it to the <tr />
    // ============================
    $tr = csvRowCells.reduce(function($tr, csvRowCell){
      return $tr.append($("<td>/</td>").text(csvRowCell));
    }, $tr);
    // ============================

    // Add our new <tr /> to the table then return the table
    return $table.append($tr);
  }, $table);
  // ============================

  return $table;
}
// ============================

// ============================
// Given an array of rows, randomly select one (as an array) and build a table with it.
// ============================
function fillContainerWithTable(csvRows, $container){
  var randomRow = [csvRows[Math.floor(Math.random() * csvRows.length)]];
  var $table = buildTable(randomRow);
  $container.append($table);
}
// ============================

// ============================
// the click handler
// ============================
function myFunction(){
  // some random csv I found...
  var uri = "https://docs.google.com/spreadsheets/d/1VNgGeM-dZ_1XpMLNzggwvRD3sRriNAGbMYwuv3ys68Y/pub?output=csv";
  var $container = $("#wrap");

  // You probably want a clean slate.
  $container.empty();

  // ============================
  // If we have the data locally already just use it.
  // ============================
  if (csvRows.length !== 0){
    console.log("using local data...");
    fillContainerWithTable(csvRows, $container);
    return;
  }
  // ============================

  console.log("fetching remote data...");

  $.get(uri, function(data){
    csvRows = data.split("\n");
    fillContainerWithTable(csvRows, $container);
  });
}
// ============================
body {
  font-family: arial, helvetica, sans-serif;
  font-weight: normal;
  font-size: 13px;
  color: #000;
  text-align: left;
  margin: 3px 0px;
}

#wrap {
  padding: 20px;
}

#wrap table {
  border: solid 1px;
  border-collapse: collapse;
  background-color: aliceblue;
  width: 100%;
}
<button onclick="myFunction()">Click me</button>
<div id="wrap"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
JonSG
  • 10,542
  • 2
  • 25
  • 36
  • thanks! thats really useful, but i'm unsure on how to switch out the google CSV for my own. – gezer4000 Sep 01 '16 at 15:02
  • set **var uri = "path to your csv";** – JonSG Sep 01 '16 at 15:41
  • I tried that and i just get a _"Control-Allow-Origin' header is present on the requested resource"_ error. – gezer4000 Sep 01 '16 at 16:04
  • You are running into a CORS Issue. The server must be configured to allow cross origin sharing. see: http://stackoverflow.com/questions/20442628/cors-jquery-ajax-request You might have more luck if you were able to return a JSON(p) response. – JonSG Sep 01 '16 at 17:15