0

I built a small PHP script which creates an Excel spreadsheet and forces its download, by defining the corresponding header. When I call this script directly by its URL (or even through JS with window.location.replace), everything works fine. Now, when I call the same script via an Ajax call (both synchronously and asynchronously) nothing happens.

Can somebody explain this behavior?

Regards Sebastian

Sebastian Dine
  • 815
  • 8
  • 23
  • 1
    Download with ajax will always fail. Why do you need ajax for this task? –  Apr 16 '18 at 12:02
  • 1
    Possible duplicate of [Download a file by jQuery.Ajax](https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax) – bigwolk Apr 16 '18 at 12:02
  • I do not desperately need ajax for this, but am interested in the reason for this behavior. – Sebastian Dine Apr 16 '18 at 12:06
  • After PHP finishes or fails creating the Excel file, it needs to send some sort of success/failulre message back to your AJAX which then needs to either provide an error or you need to [redirect](https://stackoverflow.com/a/506004/2191572) the user to some sort of dedicated download page which does not rebuild the Excel file. – MonkeyZeus Apr 16 '18 at 12:45

1 Answers1

1

AJAX requests are processed in the background, so the download headers will be ignored and only passed to your callback.

If you want to force download the file without redirecting him to the page you can

  • inject an iframe to the page and pass the download url as src-parameter
  • link to the download url with an a-tag and add the HTML5 download-attribute to it
  • put the result of your ajax-request base64-encoded in an injected a-tag as src parameter and pass a download-parameter.

Example for downloading the url https://stackoverflow.com/ as "stackoverflow.html": <a href="https://stackoverflow.com/" download="stackoverflow.html">Click me!</a>

Example for downloading the text "test" as "file.txt": <a href="data:text/plain;base64,dGVzdA==" download="file.txt">Click me</a> (where dGVzdA== is "test" base64-encoded)

After injecting both a-tags you can use e.g. jQuery to simulate an user clicking on them.

tionsys
  • 181
  • 8