4

I am calling the download servlet on click of the download button. The call is an AJAX call using XMLHttpRequest object.

var xhr = new XMLHttpRequest();

xmlhttp.open("POST","servlet",true); //servlet will be the servlet name       
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');    
xmlhttp.send(....); 

xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){

        //some logic
 }}

Errors i'm getting:

The Save as dialog doesn't appear although Fiddler shows that the document in the response.

server side : header('Content-type',//mmime type); header('Content-Disposition', 'attachment; filename=test.txt');

Snap Aoe
  • 145
  • 1
  • 1
  • 11
  • 1
    That's because your `xhr.onreadystatechange` is already handling the download. You may try to use a hidden `
    ` and a hidden `
    – Passerby May 08 '15 at 09:00
  • Could you please help out with some examples? . Do I need to use an IFrame to handle the entire AJAX req ? – Snap Aoe May 08 '15 at 09:19
  • No, you don't use AJAX at all if you want to trigger a download. Just use a form and make it point to the iframe, and submit that form. – Passerby May 08 '15 at 09:22
  • Actually I freeze the screen till I get inside onreadystatechange . So I am using AJAX there.... Can I do something simillar using IFrame ,,? Is there any way I can handle the download in onreadystste change itself....? – Snap Aoe May 08 '15 at 09:46
  • I think it's still possible. Try to listen to the `load` event of the iframe. – Passerby May 08 '15 at 09:52
  • Can I handle it in onreadystatechange and explicitly call the dialog box ? – Snap Aoe May 08 '15 at 11:43
  • Just changing the window location should trigger the prompt and still stay on the same window. Just like a normal download link with href would do. – GillesC May 08 '15 at 17:21
  • @gillesc... The download is processed by a servlet and then streamed back to the browser..... – Snap Aoe May 11 '15 at 06:45
  • No it's serving a file, this is not how things get streamed... You are doing nothing else but hitting an address on a server that returns a file, doesn't change a thing apart from the browser behaviour. Why would the browser open a dialog when data is requested via AJAX and returned to the code and not the user. If you want the user to get a save as dialog then you need to serve a file to the user not the code. Not like this wasn't asked before on here http://stackoverflow.com/questions/6668776/download-file-through-an-ajax-call-php – GillesC May 11 '15 at 09:38

0 Answers0