I am trying to create an anchor in js and click it in such a way to trigger the download of a file. This is my code:
var anchor = $('.vcard-hyperlink');
var windowUrl = window.URL || window.webkitURL;
anchor.attr({
href: 'data:text/plain;base64,' + btoa(unescape(encodeURIComponent(request.response))),
download: 'test.xml',
});
anchor.get(0).click();
where request.response is just a document coming from a server. the problem I have is that anchor.get(0) results to be undefined. How can I fix this? thanks in advance
UPDATE: this is the whole scenario
var request = new XMLHttpRequest();
request.open('GET', url + formatParams(data));
request.setRequestHeader('Authorization', 'Bearer ' + appsecurity.getBearerTokenWithoutHeader().accessToken);
request.onreadystatechange = function () {
if (request.readyState == XMLHttpRequest.DONE) {
var str = request.response;
var maxSizeForBase64 = 1048576; //1024 * 1024
var anchor = $('.vcard-hyperlink');
var windowUrl = window.URL || window.webkitURL;
anchor.attr({
href: 'data:text/plain;base64,' + btoa(unescape(encodeURIComponent(request.response))),
download: 'test.xml',
});
anchor.trigger('click');
}
}
}
request.send(data);
this is the whole method called by just a button on the client