Display image on the site

I am trying to display an image after getting the image using ajax but it doesn’t display. I can’t seem to figure out what I did wrong. From the console.log(data.image); i can see the image but it just won’t display on the page.


URL="testurl";
function getdata() {
    let xhr = new XMLHttpRequest();
    let img2 = document.getElementById("image");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.responseText);
            var data = JSON.parse(xhr.responseText);
            var image = document.createElement("img");
            image.src=data.image;
            img2.appendChild(image);
            
        }

        xhr.open('GET', URL);
        xhr.send();
    }


You could use old way and do like what you do now, but much easier way is to use the fetch method.

Take a look at this doc.

Thanks, how to i append the image value of an image to a url for example i have the image value ```
image.src=data.image;
which i have fetch and i want to append the value to the url ://test/testsomething/img/

I am assuming the URL you fetch is returning an image. You can do something like

fetch(URL).then(res => res.json()).then(data => {
  var image = document.createElement("img");
  image.src = data
})

Now you can append this image to a place you want.

Thanks, heaps very much appreciated.