Reputation: 5278
After a user fills out an email verification form (which is submitted via AJAX), I want to force a download to start in the current browser window if the AJAX call response is successful.
The email verification form looks like:
<form id="form_download_email" method="POST" action="music_email_verification.php">
<input id="download_email" type="text" tabindex="1" /> <br/>
<a href="javascript:void(0);" id="download_email_button">
Download!
</a>
</form>
The js/jquery once the "download_email_button" is clicked looks like this:
$("#download_email_button").click(function() {
var action = $("#form_download_email").attr('action');
var form_data = {email: $("#download_email").val()};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response){
if(response == 'success'){
window.location.assign('URL to .mp3 or ZIP');
}
}
});
});
The response=='success' block gets entered, and for now the only solution I found to force a download of a file without launching a pop up window (through window.open - which gets blocked by Chrome anyway), is to use window.location.assign as shown above. Is this the correct way of going about forcing a file download through JS??
However, using the window.location.assign method I can only download 1 file, and if I try to put in two lines with two mp3s, it doesn't work. AKA:
window.location.assign('http://song1.mp3');
window.location.assign('http://song2.mp3');
I do not want the user to have to click on another link after submitting the form to have to download the .mp3/.zip, I want to try to do it all in JS/jQuery.
The final method I thought about was on response=='success' to have the browser click on two hidden tags on the document that had their href pointing to the mp3s. However, it seems that "The issue is that you can't trigger a link's default action via a click" with jquery, just the onclick attribute.
Should I be doing this with js? If there is no way to do this, should I try something like PHP?
Any suggestions on the current way I do it or recommendations on how to download multiple mp3 files would be helpful!
Upvotes: 4
Views: 5131
Reputation: 8510
create an iframe for each url to download and set the iframe's source to files url :)
var
urls = ['url_1.mp3', 'url_2.mp3', /* ... , */ 'url_N.mp3'],
doLoad = function(url){
$("<iframe />")
.css("display", "none")
.bind("load", function(e){
this.src == url && $(this).remove();
})
.attr("src", url)
.appendTo($(document.body));
};
for( var i=0; i < urls.length; i++ ) {
doLoad( urls[i] );
}
Upvotes: 3