Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  143] [ 1]  / answers: 1 / hits: 145118  / 10 Years ago, tue, july 1, 2014, 12:00:00

Update 20140702:





(but I'm marking one of the other answers as accepted instead of my own,
as it got me halfway there, and to reward the effort)






It appears that setting a HTTP request header is not possible through links with <a href=...>, and can only be done using XMLHttpRequest.



However, the URL linked to is a file that should be downloaded (browser should not navigate to its URL), and I am not sure is this can be done using AJAX.



Additionally, the file being returned is a binary file, and AJAX is not intended for that.



How would one go about triggering a file download with a HTTP request that has a custom header added to it?



edit: fix broken link


More From » ajax

 Answers
17

Try


html


<!-- placeholder , 
`click` download , `.remove()` options ,
at js callback , following js
-->
<a>download</a>

js


        $(document).ready(function () {
$.ajax({
// `url`
url: '/echo/json/',
type: "POST",
dataType: 'json',
// `file`, data-uri, base64
data: {
json: JSON.stringify({
"file": "data:text/plain;base64,YWJj"
})
},
// `custom header`
headers: {
"x-custom-header": 123
},
beforeSend: function (jqxhr) {
console.log(this.headers);
alert("custom headers" + JSON.stringify(this.headers));
},
success: function (data) {
// `file download`
$("a")
.attr({
"href": data.file,
"download": "file.txt"
})
.html($("a").attr("download"))
.get(0).click();
console.log(JSON.parse(JSON.stringify(data)));
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
}
});
});

jsfiddle http://jsfiddle.net/guest271314/SJYy3/


[#70366] Saturday, June 28, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
Sun, Dec 5, 21, 00:00, 3 Years ago
Mon, Jun 14, 21, 00:00, 3 Years ago
Mon, Jul 22, 19, 00:00, 5 Years ago
Mon, Jul 8, 19, 00:00, 5 Years ago
;