Tak
Tak

Reputation: 167

How to use <img src= > with Ajax call

I am trying to insert pictures to id "pokedex-view" by using Ajax GET. I think "spriteurl" is showing the correct path. But does not work correctly, and it cannot find the pciture for the local folder. Is there something wrong in this code. Thanks.

    function populatePokedex() {

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all");
    xhr.onload = function(){
        if (this.status == 200) {
            var picArr = this.responseText.split("\n");

            for(var i=0; i < picArr.length; i++){
                var eachName = picArr[i].split(":")
                var spriteurl = "/Pokedex/sprites/" + eachName[1];
                document.getElementById("pokedex-view").innerHTML += spriteurl
                document.getElementById("pokedex-view").innerHTML += "<img src = spriteurl>";
            }
        } else {
            document.getElementById("pokedex-view").innerHTML = "ERROR: Status: " + this.status + ", " + this.statusText;
        }
    }
    xhr.onerror = function(){
        document.getElementById("pokedex-view").innerHTML = "ERROR";
    }
    xhr.send();
    }

Upvotes: 1

Views: 1315

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

Try to concatenate or to interpolate the way you assign the spriteurl as the src attribute:

document.getElementById("pokedex-view").innerHTML += '<img src="' + spriteurl + '">'

Or:

document.getElementById("pokedex-view").innerHTML += `<img src="${spriteurl}">`

Upvotes: 2

Related Questions