If I have an AJAX call that returns, say, a CSV, how do I get the browser to prompt the user for a download? Below, the ProductsExport will return the CSV in the success data. I just need what I’d replace the // Deliver file to user line with…
$.ajax({
type: "POST",
url: "/Search/ProductsExport",
data: $('#CustomerId').serialize(),
success: function (data) {
// Deliver file to user!!
},
error: function (xhr, textstatus, errorThrown) {
alert('Error');
}
})
My C# code on the back end looks like so:
var aFileContent = Encoding.ASCII.GetBytes(export);
var aMemoryStream = new MemoryStream(aFileContent);
return File(aMemoryStream, "text/plain",
string.Format("{0}.csv", CustomerId));
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You cannot as far as I’m aware. You can’t use ajax here as a file download.
YEs – its a support datatype as per jQuery but not for a file. You need to link to the file for a non ajax request either via a link or a jQuery get request.
See:
Unable to open download save dialog
and
“datatype” on
http://api.jquery.com/jQuery.ajax/
Method 2
Alternative solution to your problem is have an AJAX function return an actual URL that will download csv (similar to your C# backendcode). The client side will then launch the URL using window.open(url)
Method 3
Why does it have to be ajax? Just build your url and do a window.location.href to execute your call. All you seem to be passing it is a customerId, so that should be pretty easy.
Ajax operations are meant to allow a user to stay on the page while operations continue behind the scenes. A file download will keep the user on the page and just download the file, so there’s no benefit to using ajax in this siutation. Something like this perhaps:
window.location.href = "/Search/ProductsExport?" + $.param($('CustomerId'))
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0