jQuery how to trigger event after form post returns?

Chris picture Chris · Nov 23, 2012 · Viewed 7.9k times · Source

I have an expensive form action that builds a zip file on the server and returns it to the browser.

<form action='/download' method='post'>

<input type='submit' value='download'/>

</form>

I want to block the page on click of the button so that the user doesn't repeatably hit the button.

However I want to unblock the page after the form returns.

How can trigger an event on successful completion of the form?

(I know I can trigger this by changing the form to be an ajax submission but then the save file dialog does not appear...)

Any suggestions?

Thanks

Answer

Kyle picture Kyle · Nov 23, 2012

One way you could handle this without using AJAX could be submitting the content of the form to an iframe element. If you attach an onsubmit function to the form that disables further submissions and attach an onload function to the iframe, you should be able to disable the user from submitting the form multiple times.

Example HTML:

<form action="/download" method="post" target="downloadFrame" onsubmit="return downloadFile();">
  <input type="submit" value="download" />
</form>
<iframe style="width: 0px; height: 0px;" scrolling="no" frameborder="0" border="0" name="downloadFrame" onload="downloadComplete();"></iframe>

Example Javascript:

var downloading = false;
function downloadFile() {
    var isDownloading = downloading;
    downloading = true;
    return !isDownloading;
}
function downloadComplete() {
    downloading = false;
}