How to save user form inputs as a csv file in javascript

Viewed 31

I have two html files and i want to save specific values from those files in a csv format in javascript. I am very new to javascript and i am trying to develop a GUI for speech data collection.

My code


    var number = document.getElementById('number').value
      var student = document.getElementById('student').value
      var csvFileData = [  
       [number, student],   
    ];  
        
    //create a user-defined function to download CSV file   
    function download_csv_file() {  
      
        //define the heading for each row of the data  
        var csv = 'Name,Profession\n';  
          
        //merge the data with CSV  
        csvFileData.forEach(function(row) {  
                csv += row.join(',');  
                csv += "\n";  
        });  
       
        //display the created CSV data on the web browser   
        document.write(csv);  
      
         
        var hiddenElement = document.createElement('a');  
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);  
        hiddenElement.target = '_blank';  
          
        //provide the name for the CSV file to be downloaded  
        hiddenElement.download = 'data.csv';  
        hiddenElement.click();

My questions:

  1. Is it possible to to save data from another HTML file in the same csv file generated because everytime i try to save data from the other HTML file the old one gets replaced.
  2. How to update the sheet in the backend without downloading the sheet every time.

Thank you

1 Answers

As the web is essentially state-less, you will lose all page info when you navigate to a new page. However there are some technics you can use to preserve the info:

  1. Save the info in Session Storage, which is basically temp storage in the browser, that you could reload in the new page until you decide to download.

  2. You can use Ajax or SPA(Single Page Application), so you do not navigate to a new page but unload/load parts of the same page, in that way you never lose your hidden data that should be placed in some part of the page that will not unload.

  3. Use Redux, that is a State Container for this purpose.

Related