<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@2.1.1" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="jquery.binarytransport.js"></script>
<script src="script.js"></script>
</head>
<body>
<button>download pdf</button>
</body>
</html>
$(function() {
$("button").click(function() {
$.ajax({
url: "http://cors.jejaju.com/Snickerdoodles.pdf",
type: "GET",
dataType: 'binary',
success: function(result) {
var url = URL.createObjectURL(result);
var $a = $('<a />', {
'href': url,
'download': 'document.pdf',
'text': "click"
}).hide().appendTo("body")[0].click();
setTimeout(function() {
URL.revokeObjectURL(url);
}, 10000);
}
});
});
});
/* Styles go here */
Written for https://forum.jquery.com/topic/download-a-file-via-ajax#14737000005999144
/**
*
* jquery.binarytransport.js
*
* @description. jQuery ajax transport for making binary data type requests.
* @version 1.0
* @author Henry Algus <henryalgus@gmail.com>
*
*/
// use this transport for "binary" data type
$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){
// check for conditions and support for blob / arraybuffer response type
if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob)))))
{
return {
// create new XMLHttpRequest
send: function(_, callback){
// setup all variables
var xhr = new XMLHttpRequest(),
url = options.url,
type = options.type,
// blob or arraybuffer. Default is blob
dataType = options.responseType || "blob",
data = options.data || null;
xhr.addEventListener('load', function(){
var data = {};
data[options.dataType] = xhr.response;
// make callback and send data
callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
});
xhr.open(type, url, true);
xhr.responseType = dataType;
xhr.send(data);
},
abort: function(){
jqXHR.abort();
}
};
}
});