0

Onclick javascript function need to perform two actions.

  1. download a file with window.location.href = url
  2. document.getElementById('test').submit();

I am not able to implement both. If the submit function is added, download is not working. Any thoughts on how to achieve both. Thanks.

j08691
  • 204,283
  • 31
  • 260
  • 272
user1580577
  • 5
  • 2
  • 3

3 Answers3

1
$(" selector ").click(function() {
    $("body").append(
        $("<iframe></iframe>")
        .attr("display", "none")
        .attr("src", url)
    );
    $("#test").submit();
});
Waleed Khan
  • 11,426
  • 6
  • 39
  • 70
1

Looks like you can't do that because when submit happens, previous request for that page is closed. People suggest an iframe for file download, but submit will unload old page with iframe in it, so I do not think it will work. Suppose instead of that you should use window.open(url) instead of window.location.href = url This way you will open completely new window which will download a file and submit will happen in old one.

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
  • The `iframe` is forcing a download, not showing a download page. – Waleed Khan Aug 24 '12 at 21:01
  • Yeah, I understand that. Frankly speaking I've never tried something like that. But submit will destroy a page along with iframe. So, what will happen if, for some reason, download request will return after iframe is destroyed? – Viktor S. Aug 24 '12 at 21:07
  • This worked. But any workaround with window.location.href. I don't want to prompt download in new page. – user1580577 Aug 24 '12 at 22:57
0

In head

<script type="text/javascipt">
function startDownload()
{
var url='http://server/folder/file.ext';  
window.open(url,'Download');
}
</script>

In body

<button type="button" onclick="startDownload()">Download</button>
heretolearn
  • 6,387
  • 4
  • 30
  • 53