0

I have been trying to play around with https://www.datagridxl.com

It's a Javascript script that basically provides a visual UI to explore structured data.

Getting it up and running was pretty straight forward, and I managed to integrate it with Papa.parse to get it to load CSV files from the server.

The code for this looks like:

<html>
<head>
<style>
#grid {
  height: 400px;
}
</style>
<script src="https://code.datagridxl.com/datagridxl2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>

<div id="grid"></div>

<script>

Papa.parse("https://example.com/whatever/data/data2.csv", {
  download: true,
  complete: function(results) {
    createGrid(results.data);
  }
});

function createGrid(data){
  var grid = new DataGridXL("grid", {
    data: data
  });
};

</script>


</body>
</html>

Easy enough.

So then I wanted to make it so I could grab the data from the rendered table and download it as a .csv file.

As luck would have it, there is a build in option to do just this: https://www.datagridxl.com/docs/exporting-data

All you have to do is called grid.downloadDataAsCSV();

So I updated the page to include a button and the call.

<html>
<head>
<style>
#grid {
  height: 400px;
}
</style>
<script src="https://code.datagridxl.com/datagridxl2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<button class="button" id="someButton">Save</button>

<div id="grid"></div>

<script>

Papa.parse("https://example.com/whatever/data/data2.csv", {
  download: true,
  complete: function(results) {
    createGrid(results.data);
  }
});

function createGrid(data){
  var grid = new DataGridXL("grid", {
    data: data
  });
};


someButton.onclick = function(){
    grid.downloadDataAsCSV();
}



</script>



</body>
</html>

Sadly, whenever I try and run this I get:

Uncaught TypeError: grid.downloadDataAsCSV is not a function
    at someButton.onclick (gridtest.php:34:7)

I'm not great as JS, but I don't understand why the above is failing? I'm hoping I'm just being incredibly stupid.

Any ideas much appreciated as the documentation is somewhat sparse.

Damian
  • 1
  • 1
  • The `grid` variable is defined inside a function, so it only exists inside that function. Define it outside the function. – David Sep 16 '22 at 18:17
  • Thanks. Coming from PHP I always forget how strict JS is with variable declarations. Fixed! – Damian Sep 16 '22 at 18:22

0 Answers0