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
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
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.