I need to use JQuery ajax to post a plex and sensitive data object (nested objects, arrays, and Personally Identifiable Information) to my server, where a PDF is generated and returned to the client. The client browser then should open the PDF in a new window.
Because of the nature of the data the request neither can nor should be an encoded URL - it must include the data as a JSON body.
The other questions/answers on this subject did not solve the problem in my case or do not do so pletely.
I need to use JQuery ajax to post a plex and sensitive data object (nested objects, arrays, and Personally Identifiable Information) to my server, where a PDF is generated and returned to the client. The client browser then should open the PDF in a new window.
Because of the nature of the data the request neither can nor should be an encoded URL - it must include the data as a JSON body.
The other questions/answers on this subject did not solve the problem in my case or do not do so pletely.
Share Improve this question edited Feb 5, 2018 at 0:18 Groppe asked Dec 30, 2016 at 4:29 GroppeGroppe 3,87913 gold badges46 silver badges68 bronze badges 1- See also How to build PDF file from binary string returned from a web-service using javascript, jquery-ajax-blob-arraybuffer.js – guest271314 Commented Dec 30, 2016 at 5:43
1 Answer
Reset to default 5Solution
- POST with the data in the body as JSON.
- Set the expected
Content-Type
of the response toarraybuffer
(on the client and server). - When the request has plete successfully, convert the response to a
Blob
. - Create an object url to the
Blob
and open it in a new window.
Notes
- JQuery ajax does not support the
arraybuffer
Content-Type
so the base JavaScriptxhr
must be used (if you don't have any other options). - Internet Explorer has its own functionality for handling and displaying
Blob
's, so a special case is needed. - Supported browsers does not include IE9
Code
RequestPdf = function (url, data) {
var request = new XMLHttpRequest(), file, fileURL;
request.open("POST", url);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.responseType = "arraybuffer";
request.send(data);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
file = new Blob([request.response], { type: 'application/pdf' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE
window.navigator.msSaveOrOpenBlob(file);
} else {
fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
}
};
};