Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
How to set an image's src from the API response?

I have this code that gets an image from the Minecraft API via uuid or username. It gets the value from an input tag.

HTML:

<input type="text" id="nameinput" placeholder="Username"/>
<img src="" id="display"/>
<script type="text/javascript" src="/JS/login-page.js"></script>

Js:

document.querySelector("#nameinput").oninput = function(){
    var request = new XMLHttpRequest();
    request.onload = function() {
        // Grab data and assing feilds
        var response = JSON.parse(request.responseText);
        var uuid = response.id;
        
        if (typeof(uuid) == "undefined") {
            response.id = "steve";
        }
        
        document.querySelector("#display").src = "https://crafatar.com/avatars/" + uuid + "?overlay&size=512";
    };

    request.open("GET", "https://api.year4000.net/minecraft/" + document.querySelector("#nameinput").value, true);
    request.send();
}

Basically, I want to move the image from the API over to display it in the image tag. How do I do this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I recommend using addEventListener instead of setting the oninput attribute.

const nameInput = document.querySelector("#nameinput");
const img = document.querySelector("#display");

nameInput.addEventListener('input', function () {
    
    // Don't do anything if the value is empty
    if (this.value === '') return;
    
    const request = new XMLHttpRequest();
    request.onload = function () {
        const response = JSON.parse(request.responseText);
        const { id } = response;
        img.setAttribute('src', `https://crafatar.com/avatars/${id}?overlay&size=512`);
    };
    request.open("GET", "https://api.year4000.net/minecraft/" + this.value, true);
    request.send();
});
<input type="text" id="nameinput" placeholder="test123" /><br>
<img id="display" src="" />

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!