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>