Reputation: 1472
I am trying to convert js object to csv, using jquery foreach, Here is what the object looks like
In object 0 it has email : "[email protected]"
and fullname : "farhana"
I followed a example from stackover flow and I thought it works, but the CSV file doesn't get downloaded, or show me any message.
Here is the code
self.downloadCSV = function(){
$.ajax({
type: 'GET',
url: BASEURL + 'index.php/admin/getcsv/' + auth ,
contentType: 'application/json; charset=utf-8',
})
.done(function(docs) {
if(docs == null){
alert('file not found for csv');
}else{
// Here is where the foreach and storing to csv starts.
console.log(docs);
var csvContent = "data:text/csv;charset=utf-8,";
$.each(docs, function (index, doc) {
var dataString = doc.join(",");
csvContent += index < doc.length ? dataString+ "\n" : dataString;
});
var encodedUri = encodeURI(csvContent);
window.open(csvContent)
}
})
.fail(function(xhr, status, error) {
alert(error);
})
.always(function(data){
});
}
No error so not sure what to debug :( Need help.
Upvotes: 0
Views: 85
Reputation: 5075
window.open(csvContent)
doesn't do anything since its not a URL.
you need to create a Blob
to download content.
also your conversion from json
to csv
is wrong. doc.join(",")
only works when doc
is an Array
but your picture says its an Object
so you need to do it differently
var docs = [{ name: 'test', id: 22, emal: '[email protected]' }, { name: 'test2, sample', id: 2122, emal: '[email protected]' }, { name: 'test3', id: 2223.23, emal: '[email protected]' }];
// convert js object array to csv string
// if your "doc" is an Object
var csv = docs.reduce((str, doc) => str += '"' + Object.values(doc).join('","') + '"\r\n', '"' + Object.keys(docs[0]).join('","') + '"\r\n');
// if your "doc" is an Array
// var csv = docs.reduce((str, doc) => str += '"' + doc.join('","') + '"\r\n', '');
// download csv string as blob
var blob = new Blob([csv], { 'type': 'application\/octet-stream' });
var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = 'docs.csv';
a.click();
a.remove();
Upvotes: 1