Downloading Files with Javascript

I recently built a function which was supposed to generate a file and download it from a website.
The idea was that you had a list of items, you selected a number of them and hit post.
The selected items was posted via AJAX to a PHP script and that PHP script responded with a file that you would be able to download directly (ie. instead of actually showing a web page, the browsers download window should open. This didn’t work.

At first I couldn’t understand what was wrong and assumed that my PHP script somehow messed the file up but in the end it turned out to be AJAX. The browser received the contents of the file and the headings were correct and everything looked good but it still didn’t work.
I changed the call to standard JavaScript and it worked like a charm.

window.location = '';

So the conclusion is: Don’t use AJAX when you want to initiate a file download in the browser, use window.location instead.

Write Comment


Comment Preview


10 Most Recent Twits

Loading twits...