0

I'm making a website with a small iframe. The content of this iframe changes on choices I make somewhere else. But there might be as many as 50 small html-pages to be opened. I thought to put the data of these pages in a csv-file, so I only have to keep the csv updated, and not all the pages. In the csv there is a header, a text, a link to a picture and a caption.

And it works. But I already know the location of this csv-file. I do not want a filepicker. Is there an easy way to tell the script where to find this csv-file?

I tried to put the filename in the reader.readAsText formula. (reader.readAsText("ventilatie.csv"), but it gives me errors all along. It cannot be that hard, can it?

The csv looks like this (in Dutch):

csv-file

The code of my html page is:

    <table>
        <tr>
        <td><h2 id="koptekst"></h2></td>
        <td><button onclick="history.back()" style="float:right">Terug</button></td>
        </tr>
        <tr>
            <td><p id="uitleg"></p></td>
            <td><p><img id="plaatje" style="width:180px"></p>
            <p id="bijschrift"></p></td>
        </tr>
    </table>
    
    <script>
        window.onload = () => {
            let reader = new FileReader(),
                picker = document.getElementById("picker");
            
            picker.onchange = () => reader.readAsText(picker.files[0]);
            reader.onloadend = () => {
                let csv = reader.result;
                
                let rows = csv.split("\r\n");
                let row = rows[3].split(";");
                document.getElementById("koptekst").innerHTML = row[1];
                document.getElementById("uitleg").innerHTML = row[2];
                document.getElementById("plaatje").src = row[3];
                document.getElementById("bijschrift").innerHTML = row[4];
            }
        }
    </script>
</body>
2
  • You can use fetch to load a file, but you must have an http server that will serve it Commented Dec 31, 2022 at 17:03
  • Take this and change the comma for ; - Ik was het aan het doen, maar mijn familie wil dat ik oud-en-nieuwd viert Commented Dec 31, 2022 at 17:27

3 Answers 3

1

You can use the fetch api to read the file and the callback to parse and process the csv data. The callback here uses much of the original code

window.onload=()=>{
    const callback=(r)=>{
        let rows=r.split('\r\n');
            rows.forEach( ( row, index )=>{
            if( index > 0 ){
                let [ id, title, oms, pla, bij ] =row.split(';');
                console.log( id, title, oms, pla, bij );
            }
        })
    };
    fetch('ventilatie.csv')
        .then(r=>r.text())
        .then(callback)
        .catch(alert)
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that worked. I only needed one row, so I changed it a bit. Now I only have to change the number of the row I need. Fetch gave a error first, so I moved the site to the cloud.
0

You might want to take a look at this:

function download(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}

// Start file download.
document.getElementById("dwn-btn").addEventListener("click", function(){
    // Generate download of hello.txt file with some content
    var text = document.getElementById("text-val").value;
    var filename = "hello.txt";
    
    download(filename, text);
}, false);

https://jsfiddle.net/ourcodeworld/rce6nn3z/2/

Source: https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server

1 Comment

I think you did not read the question correctly.
0

Here is my version. You can swap the file input for a fetch

// https://stackoverflow.com/a/14991797/295783
const parseCsv = str => { let arr = [], quote = false; for (let row = 0, col = 0, c = 0; c < str.length; c++) { let cc = str[c], nc = str[c + 1]; arr[row] = arr[row] || []; arr[row][col] = arr[row][col] || ''; if (cc == '"' && quote && nc == '"') { arr[row][col] += cc; ++c; continue; } if (cc == '"') { quote = !quote; continue; } if (cc == ';' && !quote) { ++col; continue; } if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; } if (cc == '\n' && !quote) { ++row; col = 0; continue; } if (cc == '\r' && !quote) { ++row; col = 0; continue; } arr[row][col] += cc.trim(); } return arr; };

const format = csv => {
//  let rows = parseCsv(csv); // remove the comment
  let rows = parseCsv(testCsv); // delete the line
  const headerRow = rows.splice(0,1).flat();
  const [cell0,cell1,cell2,cell3,cell4] = headerRow; // seems not to be of use

  document.getElementById("tb").innerHTML = rows.map(row => `<tr>
      <td>
        <h2 id="koptekst">${row[1]}</h2>
      </td>
      <td><button onclick="history.back()" style="float:right">Terug</button></td>
    </tr>
    <tr>
      <td>
        <p id="uitleg">${row[2]}</p>
      </td>
      <td>
        <p><img id="plaatje" src="${row[3]}" style="width:180px"></p>
        <p id="bijschrift">${row[4]}</p>
      </td></tr>`).join('');

};

window.addEventListener("DOMContentLoaded", () => {
  // or fetch
  const fileInput = document.getElementById("picker");
  fileInput.addEventListener("change", () => {
    const [file] = fileInput.files;
    if (file) {
      const reader = new FileReader();
      reader.addEventListener("load", format)
      reader.readAsText(file);
    }
  })
})
<input type="file" id="picker" />
<table>
  <thead id="th"></thead>
  <tbody id="tb"></tbody>
</table>

<script>
// test data

const testCsv = `Nr; Titel; Omschrijving; Plaatje; Bijschrift
1.; Ventilatierooster; uitleg 1; plaatje 1;bijschrift 1
2.; Toevoerrooster; uitleg 2; plaatje 2;bijschrift 2
3.; Overstroomvoorziening; uitleg 3; Deurrooster.jpg; Deurrooster
4.; Afvoerrooster; uitleg 4;plaatje 4;bijschrift 4
5.; Ventilatiekanaal; uitleg 5;plaatje 5;bijschrift 5
6.; Toevoerventilator; uitleg 6;plaatje 6;bijschrift 6
7.; Afvoerventilator;uitleg 7;plaatje 7;bijschrift 7
8.; Balansventilatie-unit; uitleg 8;plaatje 8;bijschrift 8`
</script>

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.