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