Get image thumbnail in XMLHttprequest - javascript

I am trying to get image thumbnail in my XMLHttprequest but when I try I get an error "Uncaught TypeError: Cannot read property 'thumbnail' of undefined
at XMLHttpRequest.xhr.onload (app.js:73)"
Same issue for infoLinks:
Request
Could anyone help?
Thank you.
here is my code:
const btnRechercher = document.getElementById('btn-rechercher');
let bookSearch = document.querySelector('.modal-content').value;
const listElement = document.querySelector('.list-books');
const template = document.getElementById('book-template');
function searchBookHandler () {
let title = document.getElementById('titre-livre').value;
let author = document.getElementById('auteur').value;
let search = title + author;
console.log(search);
const xhr = new XMLHttpRequest();
xhr.open('GET', "https://www.googleapis.com/books/v1/volumes?q=" + search);
xhr.responseType = 'json';
xhr.onload = function() {
const listOfBooks = xhr.response;
console.log(listOfBooks);
for (i=0; i < listOfBooks.items.length; i++) {
const postEl = document.importNode(template.content, true);
postEl.querySelector('.id').textContent = listOfBooks.items[i].id;
postEl.querySelector('.titre').textContent = listOfBooks.items[i].volumeInfo.title;
postEl.querySelector('.author').textContent = listOfBooks.items[i].volumeInfo.authors;
postEl.querySelector('img').textContent = listOfBooks.items[i].volumeInfo.imageLinks.thumbnail;
listElement.append(postEl);
}
};
xhr.send();
}
btnRechercher.addEventListener('click', searchBookHandler, false);

Related

How show file download progress using javascript?

I am using below code to download the file to browser.
function UserAction() {
var Url = " ";
var postData = new FormData();
var xhr = new XMLHttpRequest();
xhr.open('GET', Url, true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
var blob = xhr.response;
this.saveOrOpenBlob(blob,blobName);
}.bind(this)
xhr.send(postData);
}
function saveOrOpenBlob(blob,blobName) {
//var assetRecord = this.getAssetRecord();
var fileName = blobName;
var tempEl = document.createElement("a");
document.body.appendChild(tempEl);
tempEl.style = "display: none";
url = window.URL.createObjectURL(blob);
tempEl.href = url;
tempEl.download = fileName;
tempEl.click();
window.URL.revokeObjectURL(url);
}
I want to display the download progress, I am not using any html code. My application has standard button which accept javascript action. I dont have any custom ui.
With current condition user will not know whether the file is downloading or not if it is a large file.
How can I achieve this?
Use this:
function saveOrOpenBlob(url, blobName) {
var blob;
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET', url, true);
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e) {
blob = new Blob([this.response]);
};
xmlHTTP.onprogress = function(pr) {
//pr.loaded - current state
//pr.total - max
};
xmlHTTP.onloadend = function(e){
var fileName = blobName;
var tempEl = document.createElement("a");
document.body.appendChild(tempEl);
tempEl.style = "display: none";
url = window.URL.createObjectURL(blob);
tempEl.href = url;
tempEl.download = fileName;
tempEl.click();
window.URL.revokeObjectURL(url);
}
xmlHTTP.send();
}

How to convert JSON API images from an API to base64 for display on webpage?

I am looking to parse the following page and extract every photo. I am looking to add a picture to the card http://api.openparliament.ca/politicians/.
I have been following this guide for reference: https://www.taniarascia.com/how-to-connect-to-an-api-with-javascript/ However when it runs, the pictures fail to appear. What am I doing wrong?
(function() {
const app = document.getElementById('root');
const container = document.createElement('div');
container.setAttribute('class', 'container');
app.appendChild(container);
var request = new XMLHttpRequest();
request.open('GET', 'http://api.openparliament.ca/politicians/?format=json', true);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
var data = JSON.parse(this.response);
data.objects.forEach(politician => {
const card = document.createElement('div');
card.setAttribute('class', 'card');
const h1 = document.createElement('h1');
h1.textContent = politician.name;
const p1 = document.createElement('p');
p1.textContent = `${politician.current_riding.name.en}, ${politician.current_riding.province}`
const p2 = document.createElement('p');
p2.textContent = politician.current_party.short_name.en
const img = document.createElement('img');
img.src = politician.image
container.appendChild(card);
card.appendChild(h1);
card.appendChild(img);
card.appendChild(p1);
card.appendChild(p2);
});
} else {
console.log('error');
}
}
}
request.send();
}());
The problem is the data returns a relative URL to the image. You need to prefix politician.image with the base url. Something like this:
img.src = "//api.openparliament.ca" + politician.image;
You will have the same issue when you try to link to the politician.url page as well.
The politician.image is of the form /media/polpics/ziad-aboultaif.jpg.
You have to prepend the server name as well:
img.src = `http://api.openparliament.ca/${politician.image}`

A piece of javascript in footer.php wordpress does work on PC but not on mobile

I have the following code in my footer.php on my wordpress website
var myForm = document.getElementById("questionnaire");
if (myForm) {
myForm.onsubmit = function() {
var questionDiv = document.getElementById('question-div');
var busyDiv = document.getElementById('busy');
var resultDiv = document.getElementById('result-div');
var resultList = document.getElementById('result-list');
var xhr = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/xxxxx/exec";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var result = response.result;
for (var i in result) {
var e = result[i];
if (e) {
var li = document.createElement('li');
if (e.url) {
var a = document.createElement('a');
a.href = e.url;
a.textContent = e.name;
li.appendChild(a);
} else {
li.textContent = e.name;
}
resultList.appendChild(li);
}
}
busyDiv.hidden = true;
resultDiv.hidden = false;
}
}
var form = document.getElementById('questionnaire');
var formData = new FormData(form);
var fields = ['name','email','yob','gender','xxx','yyyy'];
var params = [];
for (var i in fields) {
var field = fields[i];
params.push(field + "=" + formData.get(field));
}
xhr.send(params.join('&'));
questionDiv.hidden=true;
busyDiv.hidden=false;
return false;
};
}
</script>
This has allowed me to write and quote data from a google sheet
Now all this works on PC but it delivers 404 not found error on mobile site and the website itself is preset to be mobile responsive.
Can somebody help please?
Jane
What does your form html look like? I suspect that your mobile browser is trying to submit the form via the standard - non AJAX way and therefore is directing the browser to the url in the "action" attribute of your form. Try the following to stop this default behaviour
var myForm = document.getElementById("questionnaire");
if (myForm) {
myForm.onsubmit = function(evt) {
evt.preventDefault();

InvalidStateError in internet explorer 11 during blob creation

I'm getting an InvalidStateError at the blob creation line on IE 11. Needless to say, it works in Chrome and Firefox.
I can see that the binary data is my client side. Are there any alternatives to download this as a file?
var request = new ActiveXObject("MicrosoftXMLHTTP");
request.open("post", strURL, true);
request.setRequestHeader("Content-type", "text/html");
addSecureTokenHeader(request);
request.responseType = 'blob';
request.onload = function(event) {
if (request.status == 200) {
var blob = new Blob([request.response], { type: 'application/pdf' });
var url = URL.createObjectURL(blob);
var link = document.querySelector('#sim');
link.setAttribute('href', url);
var filename = request.getResponseHeader('Content-Disposition');
$('#sim').attr("download", filename);
$(link).trigger('click');
fireEvent(link, 'click');
} else {
// handle error
}
}
After instantiating an XmlHttpRequest with xhr.responseType = "blob"
I was getting an InvalidStateError.
However, moving xhr.responseType = "blob" to onloadstart solved it for me! :)
xhr.onloadstart = function(ev) {
xhr.responseType = "blob";
}
Spent some time on this and actually found out adding new Uint8Array works:
var blob = new Blob([new Uint8Array(request.response)], {type: 'application/pdf'});
Is not a elegant way but it works on IE8 - IE11:
var myForm = document.createElement("form");
myForm.method = "POST";
myForm.action = strURL;
myForm.target = "_blank";
var myInput = document.createElement("input");
myInput.type = "text";
myInput.name = "sim";
myInput.value = JSON.stringify(/*data to post goes here*/);
myForm.appendChild(myInput);
document.body.appendChild(myForm);
myForm.submit();
$(myForm).hide();
You need to use a BlobBuilder in that case.
From: https://github.com/bpampuch/pdfmake/issues/294#issuecomment-104029716
try {
blob = new Blob([result], { type: 'application/pdf' });
}
catch (e) {
// Old browser, need to use blob builder
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if (window.BlobBuilder) {
var bb = new BlobBuilder();
bb.append(result);
blob = bb.getBlob("application/pdf");
}
}
After much searching this worked for me on IE, Edge and Chrome
var xhr = new XMLHttpRequest();
xhr.onloadstart = function (ev) {
xhr.responseType = "blob";
};
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
if (!window.navigator.msSaveOrOpenBlob) {
var url = (window.URL || window.webkitURL).createObjectURL(xhr.response);
var aLink = document.createElement("a");
document.body.appendChild(aLink);
aLink.href = url;
aLink.download = filename;
aLink.click();
} else {
var fileData = [xhr.response];
blobObject = new Blob(fileData);
window.navigator.msSaveOrOpenBlob(blobObject, filename);
}
}
};

msgpack - unpack data from php service using js

Hi have created a XMLHttpRequest and get the resp by using the following code.
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.responseType = "text";
xhr.onload = function ()
{
debugger;
var resp = xhr.response;
var result = msgpack.unpack(resp);
};
but the response in undefined. I have checked the service from iOS and it is working fine.
Fixed by the following code. Set response type = arraybuffer.
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.responseType = "arraybuffer";
xhr.onload = function ()
{
var resp = xhr.response;
var uintDataArray = new Uint8Array(resp);
var strBytes = "";
for (var i = 0; i < uintDataArray.length; i++)
{
strBytes += String.fromCharCode(uintDataArray[i]);
}
var result = msgpack.unpack(strBytes);
};

Categories

Resources