0

i have a file download that is being initiated with a simple window.location.href command. Since i am staying on the same page i would like to call a different function that will refresh a part of the page, but this other function is not being executed after the download. Is there a way to do this? I guess Im looking for something like ajax`s "success" option.

Thanks!

Loshmeey
  • 341
  • 1
  • 5
  • 18
  • How are you staying on the same page after `window.location.href? `you should propably be waiting on async call to complete you download. – Deepak Ingole Sep 30 '13 at 17:23
  • No there isn't, but there are workarounds using ajax or cookies to check when the download has completed, and then do something. – adeneo Sep 30 '13 at 17:23
  • Im staying on the same page because i point the URL to the controller that gives me back the file with content disposition set and correct mime type. So if i would use very simple ajax post call without any processing in it, just added `success: function(){myfunc(a)}`.. could it work? – Loshmeey Sep 30 '13 at 17:27
  • 1
    Best way would probably be to set a cookie on the serverside when download has completed, and then continuously check for a cookie with javascript, and do something when that cookie is detected. – adeneo Sep 30 '13 at 17:31
  • I did not think this downloading will be that much of problem. :) Thanks for the responses! – Loshmeey Sep 30 '13 at 17:33

2 Answers2

1

Try this:

var req = new XMLHttpRequest();
req.open("POST", "your endpoint", true);
req.responseType = "blob";
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

var fileName = "fileName.pdf";

req.onload = function (event) {
    var blob = req.response;

    if (req.status === 200) {
        var link = document.createElement('a');

        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();

        //call your method her to do anything
    }
};

req.send();

//if you have any parameter, you can this
//reg.send(param)
0

A simple AJAX post call would suffice. Especially with something async and variable in time like a file download, the readyState attribute of an XMLHttpRequest is quite helpful.

Wyatt
  • 2,491
  • 15
  • 12
  • The simple ajax call did not trigger the save as window. Everything else worked fine i just need to see that window come up. Any idea how to do this? – Loshmeey Sep 30 '13 at 17:42
  • You have Content-Type: octet-stream and Content-Disposition: attachment, you said? – Wyatt Sep 30 '13 at 17:44
  • Yep, everything is set properly in the response! – Loshmeey Sep 30 '13 at 17:46
  • You might want to try creating an iframe and setting its source to the location of the file (which should be in your AJAX response) – Wyatt Sep 30 '13 at 17:46
  • i was just looking into this answer! http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery – Loshmeey Sep 30 '13 at 17:48