So I am hitting a third-party API that gives back an image. I am supposed to show the returned image in a div (which initially contains a loading image), but I am unable to do so. I have tried various ways (as I will illustrate below), but none of them work.
The browser network tab shows the request being received and the image is also displayed as the response.
My code is as follows (I have stripped it down to the bare minimum required)
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script>
$.ajax
({
type: "GET",
url:"https://third-party-api.com/path/to/rest/api/",
headers: {
"Authorization": "bearer value-of-token"
},
success: function (data){
console.log('SUCCESS');
console.log(data);
//data above is logged as jumbled characters in browser
$('#t').attr('src','data:image/jpeg,' + data);
//above line shows a broken image
$('#t').attr('src','data:image/jpeg;base64,' + btoa(data));
// above line (with base64) says there are invalid characters in string
// however the browser network tab shows image correctly
},
error: function(err)
{
console.log('ERROR')
console.log(err);
}
});
</script>
<html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<body>
<img src='loading.jpg' id='t'>
</body>
</html>
The lines
console.log('SUCCESS');
console.log(data);
prints the following in the console:
I know however that the image is correct because it shows up correctly in both the browser's network tab as well as in postman. How can I get such an image response to load correctly into the HTML div?
Any help is much appreciated!