I have a button that, when clicked on, needs to download a file by submitting a form using POST. [Edit to clarify: The file being downloaded is dynamically generated via a PHP script based on values within the hidden form (which I change via jQuery, depending on the button clicked). The file in question is an Excel file. I would prefer not to use GET if possible, since I don't want people to link directly to the file.]
I am unable to use $.post
to submit the form because this does not work as I would like. While the submission happens fine, it doesn't trigger the download dialogue box in the browser. As I understand it, the contents of the file now exist within JavaScript, and there's no way (that I know of) that allows you to send this to the browser from JavaScript for download. So, other solutions (e.g. How do I use jQuery or Ajax to swap the background image after a form is submitted?) won't work in this particular case.
The solution I found was to use the $("#someform").submit();
to fire a hidden form when the button was clicked on. The page doesn't reload, and the save dialogue pops up on screen.
Example code:
$( "#button" ).click(
function() {
$(this).removeClass( "button" );
$(this).addClass( "loading" );
$( "#form" ).submit();
}
);
However, since it could take several seconds to generate the file, I wanted to display a loading animation gif to the user. This now presents the problem that I can display the animation, but I cannot remove the animation after the form has been submitted.
If it can't be done using this method, is there a better solution someone can suggest?