0

I am using C# and JavaScript. my goal is to send an ajax request that results in a CSV file being downloaded. The CSV will be generated on the server side in an ashx page. Currently the application is able to download a CSV but by using a form instead of an AJAX request, however the backend code is the same.

Here is the ajax request I have which fails:

$.ajax({
    url: "myDir/x.ashx/exportAllData",
    type: 'POST',
    data: { 
        id:8
    },
    success: function(ajaxResult){
    console.log(ajaxResult);
    }
});

Here is the Form method that does work:

var $form = $(document.createElement('form'))
    .attr({
        action: 'myDir/x.ashx/exportAllData',
            method: 'POST'
        })
        .css('display', 'none')
        .appendTo('body');         
    $form.submit();
    $form.empty().remove();

Here is the code in the handler(C#), which is the same for both the above cases:

else if(action == "exportalldata")
{
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("test1,test2,test3,test4,test5");
       context.Response.Clear();
       context.Response.ContentType = "application/csv";
       context.Response.AddHeader("Content-Disposition",       "attachment;filename=data.csv");                
     context.Response.Write(sb.ToString());
     context.Response.End();
}
  • 2
    Properly duplicate http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax – Izikon Oct 23 '13 at 14:01

3 Answers3

1

The short answer is you can't. Browsers cannot download files via ajax. It has to be done via form post.

David L
  • 32,885
  • 8
  • 62
  • 93
  • or GET... actually it doesn't have anything to do with the Request itself, but with the "thing" handling the response. Javascript isn't able to store data in filesystem. – Laurent S. Oct 23 '13 at 14:02
  • A fair clarification. JavaScript can't interact with the disk for security reasons, since it's a vulnerability. – David L Oct 23 '13 at 14:03
0

You could modify your server-side code to output to a static file within your webroot and return a URL pointing to it. You could then set window.location.href to the URL.

Chris Pickford
  • 8,642
  • 5
  • 42
  • 73
  • that would be an idea. The file doesn't even need to be in the root as long as you've got a handler to get it from where it is. – Laurent S. Oct 23 '13 at 14:04
0

If you populate date yourself you can use this

jQuery Plugin for Requesting Ajax-like File Downloads

example from link:

$.download('/export.php','filename=mySpreadsheet&format=xls&content=' + spreadsheetData );
Ozan Yurtseven
  • 810
  • 8
  • 17