0

I am using $.ajax call for download excel from .aspx page. But ajax throwing an error after Response.End. This is the code I used. Control is processing till Response.End() then alert(textStatus); giving parser error.

MasterPage.Master

$.ajax({
  type: "POST",
  url: "../Users/DownloadExcel.aspx",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  async: true,
  success: function(msg) {
           alert(msg);
          $.unblockUI();                        
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert(textStatus);
      $.unblockUI();
  }
  });

DownloadExcel.aspx

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        GenerateData()
 End Sub
 Private Sub GenerateData()
      ' Some Logic
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    Response.AddHeader("content-disposition", "attachment;  filename=" & filename)
    Response.BinaryWrite(pck.GetAsByteArray())
    Response.End()
 End Sub
James123
  • 11,184
  • 66
  • 189
  • 343
  • 3
    Have you confirmed that the responseText contains valid JSON(since you telling jquery that it should expect json)? – Kevin B Mar 29 '12 at 21:09
  • Take a look at this answer here. http://stackoverflow.com/questions/149821/use-jquery-to-send-excel-data-using-ajax – Koen Peters Mar 29 '12 at 21:12

2 Answers2

1

Just use an html link with any necessary query string parameters... Don't use ajax to call for a file download unless you have some special reason.

Matthew Blancarte
  • 8,251
  • 2
  • 25
  • 34
0

You won't be able to download a file using $.ajax function, because it only handles text related formats (text, xml, json), and the Excel file is not.

I see you are not sending any headers or data, so perhaps using hidden iFrames, can help you.

Or maybe this: http://filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/

Mike
  • 485
  • 1
  • 4
  • 14