user623647
user623647

Reputation: 133

jQuery delivery of a file with AJAX call

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));

Upvotes: 2

Views: 6391

Answers (3)

Dan Csharpster
Dan Csharpster

Reputation: 2732

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'))

Upvotes: 0

Adam Tuliper
Adam Tuliper

Reputation: 30152

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/

Upvotes: 3

DHornpout
DHornpout

Reputation: 6510

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)

Upvotes: 0

Related Questions