Skip to content

Instantly share code, notes, and snippets.

@carlosrivera
Created April 10, 2015 15:49
Show Gist options
  • Save carlosrivera/768b0c14e083c1ab423f to your computer and use it in GitHub Desktop.
Save carlosrivera/768b0c14e083c1ab423f to your computer and use it in GitHub Desktop.
Ajax file download using an iframe
//taken from http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax
function ajax_download(url, data) {
var $iframe,
iframe_doc,
iframe_html;
if (($iframe = $('#download_iframe')).length === 0) {
$iframe = $("<iframe id='download_iframe'" +
" style='display: none' src='about:blank'></iframe>"
).appendTo("body");
}
iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
if (iframe_doc.document) {
iframe_doc = iframe_doc.document;
}
iframe_html = "<html><head></head><body><form method='POST' action='" +
url +"'>"
Object.keys(data).forEach(function(key){
iframe_html += "<input type='hidden' name='"+key+"' value='"+data[key]+"'>";
});
iframe_html +="</form></body></html>";
iframe_doc.open();
iframe_doc.write(iframe_html);
$(iframe_doc).find('form').submit();
}
$('#someid').on('click', function() {
ajax_download('/download.action', {'para1': 1, 'para2': 2});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment