Search code examples
javascripthtmlalasql

Alasql import from upload button vs file onchange event


I am trying to figure out how to import a file into ALASQL from a file input. There is documentation on how to do this but my client wants to have to press a load button vs when choosing the file.

Here is the documentation from ALASQL:

<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:&lt;/p>
<input id="readfile" type="file" onchange="loadFile(event)"/>
<script>
    function loadFile(event) {
        alasql('SELECT * FROM FILE(?,{headers:true})',[event],function(data){
            // Process data here
        });
     }
</script>

https://github.com/agershun/alasql/wiki/How%20to%20upload%20form%20for%20txt%20and%20xlsx%20in%20javascript

My client wants something like this:

<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:&lt;/p>
<input id="readfile" type="file"/>
<button onclick="loadfile()">Load</button>
<script>
    function loadFile() {
        var file=document.getElementById('readfile').files[0]
        alasql('SELECT * FROM FILE(?,{headers:true})',[file],function(data){
            // Process data here
        });
     }
</script>

I have tried various methods to achieve this but nothing has worked so far. Some of the methods I have tried include creating custom jQuery events and the above example.

I have found a SF article that asks something similar but was unanswered. Loading CSV file with AlaSQL and JQuery

Thank you


Solution

  • One answer I came up with is to split the loadfile process into two functions such as this:

    <script src="xlsx.core.min.js"></script>
    <p>Select CSV file to read:&lt;/p>
    <input id="readfile" type="file" onchange="loadfile(event)"/>
    <button onclick="loadfile2()">Load</button>
    <script>
        var loadFileTempData=[];
        function loadFile() { //load data file into variable
            var file=document.getElementById('readfile').files[0]
            alasql('SELECT * FROM FILE(?,{headers:true})',[file],function(data){
                loadFileTempData=data;
            });
         }
         function loadFile2(){ //process data from variable
             var data=loadFileTempData;
             loadFileTempData=[];
             // Process data here
         }
    </script>