Search code examples
javascriptimagecallback

JS: getting img and diplaying with callback


I'm following a tutorial to understand AJAX a bit better, i'm not a webdev so i'm not very skillful with JS, but i got my basics down, the example should be able to get an image on screen through way of a callback function, waiting until the client gets the image an displaying it once it's got it.

I know callback is kinda outdated, but since the example uses callback and next exercise is promises it should still work with callbacks, right?

Here's the example code:

function showImage(url, type, callback) {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url)
            xhr.responseType = type;

            xhr.onload = function() {
                callback(xhr.response);
            }

            xhr.send();
}

function createImage() {
            const objectURL = URL.createObjectURL(blob);
            const imageElement = document.createElement('img');
            imageElement.src = objectURL;
            document.body.appendChild(imageElement);
}

showImage('apple.jpg','blob',createImage);

but the image doesn't show.

I fiddled with it for a bit tried some basic stuff like having the url ./apple.jpg and http://localhost/apple.jpg i tried passing the url as an arg to createImage like so

function createImage(url) {
            const objectURL = URL.createObjectURL(blob);
            const imageElement = document.createElement('img');
            imageElement.src = url;
            document.body.appendChild(imageElement);
}

showImage('apple.jpg','blob',createImage('apple.jpg'));

but there's no way for the img to show on screen, i've checked out if the image is created correctly and on other posts it's pretty much the same using createObjectURL(blob), so i'm assuming it's comething with the callback that's preventing the img from showing, but i honestly don't know.

Any JS expert see what's wrong with this? I'm sure it's super simple and i'm just not seeing it.


Solution

  • The only change you have to make to your code, is add blob as a parameter to your createImage() callback function. The function already tries to use blob, and showImage() already sends the blob to createImage().

    function showImage(url, type, callback) {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', url)
                xhr.responseType = type;
    
                xhr.onload = function() {
                    callback(xhr.response);
                }
    
                xhr.send();
    }
    
    function createImage(blob) {
                const objectURL = URL.createObjectURL(blob);
                const imageElement = document.createElement('img');
                imageElement.src = objectURL;
                document.body.appendChild(imageElement);
    }
    
    showImage('apple.jpg','blob',createImage);