Reputation: 605
I have a code which converts JSON to CSV. And I put this through a specific condition ( if condition) I want the CSV to be downloaded automatically if the condition is met without any button click. what is the shortest/simplest way to do this?
For eg:
if( data.length == 10){
var stored_data = data;
data = [];
console.log(stored_data);
var csv_file = ConvertToCSV(stored_data); //ConvertTOCSV is a function
}
if the above condition is met, the CSV should be downloaded. Thank you
NOTE: I know this can e done easily with a button click. but i want the download to happen automatically when the condition is satisfied
Upvotes: 0
Views: 162
Reputation: 1516
What you are trying to do is possible by changing the document location to point to your created object, but the problem that I ran into while trying to create a quick example for you, is I can't seem to give the file a usable name and extension. So everything downloaded as a file called "download" with no extension (however - the file contents are correct).
So if you want to pursue finding a way to give the stream a name and file type you could start with something like this -
document.location='data:Application/octet-stream,' + encodeURIComponent(csv_file);
But I would say that @Scott's answer is a better way to go.
Upvotes: 0
Reputation: 65796
Just create a "dummy" link and programmatically set its href and then click. The link shouldn't appear on the screen because it has no content.
<body>
<a href="#" id="csvDownload" download></a>
</body>
<script>
if( data.length == 10){
var lnk = document.getElementById("csvDownload");
var stored_data = data;
data = [];
console.log(stored_data);
var csv_file = ConvertToCSV(stored_data); //ConvertTOCSV is a function
lnk.href = csv_file;
lnk.click();
}
</script>
Upvotes: 2