Search code examples
javascriptajaxxmlhttprequestjs-xlsx

XMLHttpRequest: Access object created in oReq.onload


I am using an XMLHttpRequest and sheetjs (https://github.com/SheetJS/js-xlsx) to create a json object from an excel spreadsheet. All is working well except I am struggling to access the created object outside of oReq.onload. After creating the json object I would like to use it as the input object to more code below the XMLHttpRequest.

I have tried to return json at the end of oReq.onload and also tried include my additional code inside function (e) {} but neither option has worked. Any suggestions would be appreciated.

    /* set up XMLHttpRequest */
    var url = "graph.xlsx";
    var oReq = new XMLHttpRequest();
    oReq.open("GET", url, true);
    oReq.responseType = "arraybuffer";

    oReq.onload = function(e) {
      var arraybuffer = oReq.response;

      /* convert data to binary string */
      var data = new Uint8Array(arraybuffer);
      var arr = new Array();
      for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
      var bstr = arr.join("");

      /* Call XLSX */
      var workbook = XLSX.read(bstr, {type:"binary"});

      /* Create the json object */
      var json = to_json(workbook); 

      /*Converts excel format to JSON*/
      function to_json(workbook) {
        var result = {};
        workbook.SheetNames.forEach(function(sheetName) {
            var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
            if(roa.length > 0){
                result[sheetName] = roa;
            }
        });
        return result;
      }
    };
    oReq.send();

    /*I WOULD LIKE TO USE THE CREATED JSON OBJECT HERE*/

Solution

  • Ended up being an asynchronous problem as suggested by @epascarello. A very comprehensive explanation can be found in the post: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference