Download PDF File Using Jquery Ajax

Download and open PDF file using Ajax

You don't necessarily need Ajax for this. Just an <a> link is enough if you set the content-disposition to attachment in the server side code. This way the parent page will just stay open, if that was your major concern (why would you unnecessarily have chosen Ajax for this otherwise?). Besides, there is no way to handle this nicely acynchronously. PDF is not character data. It's binary data. You can't do stuff like $(element).load(). You want to use completely new request for this. For that <a href="pdfservlet/filename.pdf">pdf</a> is perfectly suitable.

To assist you more with the server side code, you'll need to tell more about the language used and post an excerpt of the code attempts.

Download pdf file using jquery ajax

jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion

Given that, you have one of two solutions:

First solution, abandon JQuery and use XMLHTTPRequest

Go with the native HTMLHTTPRequest, here is the code to do what you need

  var req = new XMLHttpRequest();
req.open("GET", "/file.pdf", true);
req.responseType = "blob";

req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
};

req.send();

Second solution, use the jquery-ajax-native plugin

The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it

$.ajax({
dataType: 'native',
url: "/file.pdf",
xhrFields: {
responseType: 'blob'
},
success: function(blob){
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
}
});

Download pdf file from ajax response

Any idea on how to optimize it for all modern browsers?

Yes, I can give you a solution tested on windows 10 with IE11, Firefox 47 and Chrome 52. Nothing for Microsoft Edge at the moment.

At the beginning you need to distinguish if you are on IE or the other two browsers. This because on IE11 you can use:

window.navigator.msSaveBlob(req.response, "PdfName-" + new Date().getTime() + ".pdf");

For the other two browsers your code works on Chrome but not on Firefox because you did not append the element to the document body.

So the corrected code is:

var req = new XMLHttpRequest();
req.open("POST", "/servicepath/Method?ids=" + ids, true);
req.responseType = "blob";
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {

// test for IE

if (typeof window.navigator.msSaveBlob === 'function') {
window.navigator.msSaveBlob(req.response, "PdfName-" + new Date().getTime() + ".pdf");
} else {
var blob = req.response;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "PdfName-" + new Date().getTime() + ".pdf";

// append the link to the document body

document.body.appendChild(link);

link.click();
}
}
};
req.send();

Not able to download Pdf/Excel with JQuery AJAX get request with some data sent with get request

This works

$.ajax({
url: "http://localhost:8000/get_excel",
type: "POST",
data: {data : list_of_tables},
dataType: 'binary',
xhrFields: {
'responseType' : 'blob'
},
headers: {
'Accept': "application/json",
'Authorization': 'Bearer ' + getCookie(ACCESS_TOKEN),
},
success: function (data, textStatus, request) {
alert("success in fetching data");
let url = URL.createObjectURL(data);
let $a = $('<a />', {
'href': url,
'download': 'document.xlsx',
'text': "click"
}).hide().appendTo("body")[0].click();

// URL.revokeObjectURL(url);

},
error: function (XMLHttpRequest, data) {
console.log("error in show_history");
console.log(data);
console.log(XMLHttpRequest.status);
console.log(XMLHttpRequest.responseJSON);
}
});

Download a file by jQuery.Ajax

2019 modern browsers update

This is the approach I'd now recommend with a few caveats:

  • A relatively modern browser is required
  • If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.

fetch('https://jsonplaceholder.typicode.com/todos/1')  .then(resp => resp.blob())  .then(blob => {    const url = window.URL.createObjectURL(blob);    const a = document.createElement('a');    a.style.display = 'none';    a.href = url;    // the filename you want    a.download = 'todo-1.json';    document.body.appendChild(a);    a.click();    window.URL.revokeObjectURL(url);    alert('your file has downloaded!'); // or you know, something with better UX...  })  .catch(() => alert('oh no!'));

Downloading PDF file with JQuery AJAX and PHP

i don't think this approach to downloading a pdf will work. Javascript is sending the request, and php is sending the response. You want the response to go directly to the browser, not to javascript. You should change the download link to go directly to the download location. No ajax / javascript needed. Like this:

<a href="javascript:void(0)" onclick = "window.href='app/myPage/download?'+id">download</a>


Related Topics



Leave a reply



Submit