Skip to content

Instantly share code, notes, and snippets.

@wholypantalones
Last active August 7, 2019 09:29
Show Gist options
  • Save wholypantalones/8983865 to your computer and use it in GitHub Desktop.
Save wholypantalones/8983865 to your computer and use it in GitHub Desktop.
Force download of csv response from ajax request
$.ajax({
url: "path/to/csvData",
type: "GET",
dataType: "text",
success: function (data) {
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(data);
$("#exportsags").attr({
"href": csvData,
"download": "sag_data.csv"
});
}
}); // ajax
@MiRush94
Copy link

what if I have a web api and the constructor awaits a (string pattern, string format) stuff.

@sarnad
Copy link

sarnad commented Jul 4, 2017

This will trigger the two time request

@awaisdar001
Copy link

Also It will add the whole data in the HTML.

@macielportugal
Copy link

Thanks!

var encodedUri = 'data:application/csv;charset=utf-8,' + encodeURIComponent(data);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "relatorio.csv");
link.innerHTML= "Download do Relatório";
document.body.appendChild(link);
link.click();

@Zerkk
Copy link

Zerkk commented Jun 28, 2019

Thanks, this worked for me!

@shashisingh2005
Copy link

What happen if we have a large data set. Download failed if i have data around more than 18K rows.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment