1

I need to trigger a Download of an Excel file via an Ajax request. (This must be Ajax because the rows are dynamically generated from the shown client-side DataTable, filtered etc. -- so I grab the shown GUI rows).

I trace the code both on the client-/server-side, and everything works, the workbook is generated, but the download is never triggered at the end due to an error.

$.ajax({
    url: "exportSearchResults",
    dataType: "json", /* I comment out this line or leave it in */
    type: "post",
    data: {
        'exportSearchResultsJson': JSON.stringify(result)
    },
    success: function( data ) {
        alert('Success');
        console.log(data);
    },
    error: function(xhr, error, thrown) {
        alert('Error');
        console.log(xhr + " " + error);
    }
});

ERROR: parsererror (shown in Chrome)

1) When dataType = JSON:

SyntaxError: Unexpected token P in JSON at position 0
    at JSON.parse (<anonymous>)
    at n.parseJSON 

2) When no dataType specified, I think it assumes XML:

Error: Invalid XML

Server-Side:

public String exportSearchResults() throws Exception {

        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            log.error("Failed to write into response - fileName=" + filename + ", mimeType=" + mimeType, e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    return null;
}

struts.xml:

<action name="exportSearchResults" method="exportSearchResults" class="gov.nih.nci.cbiit.scimgmt.mcs.action.SearchRequestAction">
    <result type="json">
        <param name="contentType">text/plain</param>
    </result>           
    <result name="error">/WEB-INF/jsp/content/dashboardError.jsp
    </result>
</action>
gene b.
  • 10,512
  • 21
  • 115
  • 227
  • 1
    The error means that whatever you're returning is not valid JSON – Rory McCrossan Sep 18 '18 at 14:58
  • But how do I make my return a valid binary file, e.g. Excel/application? The server-side headers are all set correcctly. – gene b. Sep 18 '18 at 15:47
  • If you want to download a file through AJAX then it's possible, but very convoluted. You need to base64 encode the file, download it, then convert from base64 to binary on the client. See [this specific answer](https://stackoverflow.com/a/29939024/519413) in the duplicate I marked – Rory McCrossan Sep 18 '18 at 15:51

0 Answers0