'File download using AJAX, jQuery and PHP
I am working on document management related system and stuck in an issue for long time. I have below mentioned jQuery code which calls a PHP API which returns binary data (image also attached with the post.
My jQuery code creates a blob url like "*blob:https://example.com/16b68a7c-b773-4320-9805-ebc1675e6745*" and it loads the url in a window after triggering click of but it didn't load any thing in the browser neither downloads any file.
Please note that I want to download file with file name which will be generated after binary data conversion (dynamically) from response.
My jQuery Code:
$.ajax( '<?php $base_url ?>',
{
data: docDeleteParams,
type: "POST",
'dataType' : 'binary',
'xhrFields' : {
'responseType' : 'blob'
},
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 2) {
if (xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
}
})
.complete(function ( xhr ) {
let blob = new Blob(xhr.response);
console.log(blob);
var $a = $( '<a />' ),
base_url = window.URL || window.webkitURL,
url = base_url.createObjectURL( blob );
$a.attr({
'href' : url,
'download' : 'document_name',
"target": "_blank"
});
$("body").append($a);
$a.click();
});
Response from API:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

