user1580577
user1580577

Reputation: 5

javascript download a file and perform submit action

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.

Upvotes: 0

Views: 4266

Answers (3)

heretolearn
heretolearn

Reputation: 6545

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>

Upvotes: 0

Viktor S.
Viktor S.

Reputation: 12815

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.

Upvotes: 1

Waleed Khan
Waleed Khan

Reputation: 11467

$(" selector ").click(function() {
    $("body").append(
        $("<iframe></iframe>")
        .attr("display", "none")
        .attr("src", url)
    );
    $("#test").submit();
});

Upvotes: 1

Related Questions