Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  54] [ 4]  / answers: 1 / hits: 16744  / 10 Years ago, tue, december 2, 2014, 12:00:00

The following code works in both FireFox and Chrome, but not IE. Essentially, I have a JSON object which gets converted into an array and then to a csv format, when I click the button in FF or Chrome the file gets downloaded or the Save As window opens, but in IE a new tab opens up. In a perfect world IE would not exists, but in the real world we have to make it work, lol.



$(#csvbtn).click(function(e){
e.preventDefault();
var json_obj= JSON.parse(result);
var csv = JSON2CSV(json_obj);
window.open(data:text/csv;charset=utf-8, + escape(csv));
});


BTW, I am using IE 11 in windows 8 to test this, if that makes a difference.



Thanks all!


More From » jquery

 Answers
4

This is my solution in case someone else is looking for a solution. now it works with FF, Chrome , and IE



var csv = JSON2CSV(json_obj);            
var blob = new Blob([csv],{type: text/csv;charset=utf-8;});

if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, csvname.csv)
} else {
var link = document.createElement(a);
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute(href, url);
link.setAttribute(download, csvname.csv);
link.style = visibility:hidden;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}


Now I just need to figure out if there is a way to have the save as screen pop up instead of automatically saving the file. If anybody knows the answer to that please share. For now my users will have to use this functionality.



Thanks all for all the great answers, you guys are awesome.


[#68614] Monday, December 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alli

Total Points: 409
Total Questions: 101
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
alli questions
Sat, Apr 23, 22, 00:00, 2 Years ago
Mon, May 18, 20, 00:00, 4 Years ago
Tue, Mar 24, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;