Incorporating a Random Image Generator API into JavaScript to show images on an HTML page

I'm just starting out with programming.

Currently, I am working on a project for school that involves displaying random dog images using an API. However, I keep encountering a 404 error even though I can see the URL changing and the dog breed updating in the console log. Instead of the expected photo, I only see a broken image icon on my HTML page.

Below is the code snippet I have:

let xhrdog = new XMLHttpRequest();   //AJAX request for dog photos from API
xhrdog.onreadystatechange = function() {

  if (xhrdog.readyState === 4) {
    if (xhrdog.status === 200) {
      let ajdog = JSON.parse(xhrdog.responseText); 
      let image = document.createElement('img')
      image.src = ajdog   //xhrdog.responseText;
      let dog = document.getElementById('dog')
      dog.appendChild(image);
    }
  }
}

xhrdog.open('GET', 'https://dog.ceo/api/breeds/image/random');
xhrdog.send();

Any assistance or guidance on this issue would be highly appreciated.

Answer №1

You are so close to completing the task. The issue lies in the fact that the service is returning more than just the image URL, as you noticed in the console. It actually sends a JSON string, which you correctly parse.

Once parsed, you end up with an object, not just a plain string, stored in ajdog. Within this object, there is an element called 'message' that contains the direct URL to the dog image. So, make sure to access ajdog.message instead of just ajdog when setting the img.src.

Here's the modified snippet:

let xhrdog = new XMLHttpRequest(); //first ajax request, fetching dog photos from the API

xhrdog.onreadystatechange = function () {

if (xhrdog.readyState === 4) {

if (xhrdog.status === 200) {

let ajdog = JSON.parse(xhrdog.responseText);
console.log(xhrdog.responseText);//CHECK CONSOLE FOR RESPONSE
let image = document.createElement('img');

image.src = ajdog.message;   //xhrdog.responseText;

let dog = document.getElementById('dog');

dog.appendChild(image);

}
}

}

xhrdog.open('GET', 'https://dog.ceo/api/breeds/image/random');

xhrdog.send();
<div id="dog"></div>

Answer №2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fetch Random Dog Image</title>
</head>
<body>

    <img src="" alt="Random Dog Image">
    <script>
        //API to fetch random dog image
        async function randomDog(){
            //store the promise with URL
            const result = await fetch('https://dog.ceo/api/breeds/image/random').then((data)=>{
                return data.json()
            })
            //return an object
           return result
        }
        //get image element from DOM
        const img= document.querySelector('img')
        //this function is returning a promise 
        randomDog().then((data)=>{
            img.setAttribute('src',data.message)
        })
    </script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The server's response contained a MIME type of "application/octet-stream" that did not include JavaScript. Module scripts in HTML are subject to strict MIME type checking

Here is the structure of my project: node_modules server.js public: glsl: fragment.glsl vertex.glsl index.html main.js img.jpg style.css I have set up a simple server to serve a three.js animation in server.js const express = require('expre ...

Issues with IE not recognizing the appendChild() Javascript method

Can someone please help me troubleshoot why this code snippet is not functioning properly in Internet Explorer but works fine in Firefox? I am fairly new to using the appendChild() method. <html> <head> <script type='text/javascript&ap ...

Using the getElementById function in javascript to modify CSS properties

Here is the setup I am working with: <div id="admin"> This element has the following style applied to it: display: none; I am attempting to change the display property when a button is pressed by defining and utilizing the following JavaScript co ...

How can I programmatically close an md-select when a button is clicked within the md-select?

How do I close the md-select menu when a button inside it is clicked? JavaScript $scope.closeSelectBox = () => { var esc = jQuery.Event("keydown"); esc.which = 27 esc.keyCode = 27 $(document).trigger(esc) } HTML <md-input-container style ...

When errors occur while printing HTML through an Ajax request, it can hinder the functionality of other JavaScript code

I recently conducted an interesting experiment on my website. The concept involved sending an AJAX request to a PHP file, which then retrieved a random website by using various random words for search queries on Google. The retrieved website content was th ...

Using Javascript to dynamically add variables to a form submission process

Looking to enhance my javascript skills, I've created a script that locates an existing id and exchanges it with a form. Inside this form, I'm aiming to incorporate javascript variables into the submit url. Unsure if this is feasible or if I&apo ...

Enhance Your Website with HTML and JavaScript

Here is the code snippet I am working with: sTAT **javascript** var acc = document.getElementsByClassName("item-wrapper"); var i; for (i = 0; i < acc.length; i++) { acc[i].onclick = function(){ this.classList.toggle("selected"); this.nextElementS ...

What is the browser location for storing JavaScript constants?

How can I retrieve the value of a constant using a string as its name, where the constant is an arrow function? const foo = (bar) => { return bar } I tried accessing it through the window object but got undefined: let fn = window['foo'] // ...

How can the propagation of swipe events from a child to a parent be prevented?

I am facing an issue with my slides where users can swipe to navigate between different slides. Some slides contain carousels or nested slides, and when I swipe the carousel, it also triggers the navigation of the parent slide. How can I prevent this from ...

What is the reason for elements such as "if" and "else" not being visually

I am currently developing a browser-based code editor with a unique feature. Task: The objective is to highlight specific keywords like if, else, for... when they are entered into the editor. textarea.addEventListener("input", function() { ...

RXJS buffering with intermittent intervals

Situation: I am receiving audio data as an array and need to play it in sequence. The data is coming in continuously, so I am using an observable to handle it. Since the data arrives faster than it can be played, I want to use a buffer to store the data w ...

What is the best way to display the latitude and longitude values stored in my database on a Google Map interface?

Currently, I have some sample code that calls latitude and longitude values and marks them on maps. However, my goal is to display all latitude and longitude records on the map, not just one. I understand that I need to modify my code to fetch all values ...

Issues with the styling of HTML code

Our website features a main menu with submenus that are intended to be displayed only when hovering over the main menu. However, upon loading the site, the submenu is already visible causing an issue. We need the submenu to appear only when the main menu i ...

I find the SetInterval loop to be quite perplexing

HTML <div id="backspace" ng-click="deleteString(''); decrementCursor();"> JS <script> $scope.deleteString = function() { if($scope.cursorPosVal > 0){ //$scope.name = $scope.name - letter; ...

Use the filter method to organize arrays into subarrays based on their length, filtering out those with a length greater than or

Hey there, I've been working on incorporating the array filter property to separate subarrays that are greater than and less than 3 into two distinct functions. Unfortunately, I'm a bit stuck on how to continue fixing my functions. Can someone pr ...

Building an LED display with three.js

I have a project where I am creating a board with multiple RGB LEDs mounted on it, as shown in the image. https://i.sstatic.net/WtOm4.png To create the LEDs, I used the following code: this.light = new THREE.PointLight(color, intensity, distance, decay) ...

Is there a way to ensure the code inside the success function of a promise object is executed before the code that comes after the function

My function, handleWidgetDrop, calls another function called insertBlankWidget which in turn executes a certain function upon the return of a promise object. The issue I am facing is that the code following the call to insertBlankWidget in handleWidgetDr ...

How to Incorporate an Anchor Link into a Div as well as its Pseudo Element using CSS, Javascript, or jQuery

How can I make both the menu item and its icon clickable as a link? When either is clicked, the link should work. Here is a CodePen example: http://codepen.io/emilychews/pen/wJrqaR The red square serves as the container for the icon that will be used. ...

Exploring the integration of AJAX callbacks with ASP.NET User controls

What is the most effective approach for integrating user controls that require AJAX callbacks? My objectives include: Utilizing browser events (such as drag and drop) to trigger an AJAX notification that can initiate a control event, allowing the code o ...

What is the process for utilizing GruntFile.coffee and package.json to extract or create the Lungo.js example files?

I want to experiment with the Lungo.js examples found here: https://github.com/tapquo/Lungo.js. However, when I try to run the index.html in the example directory, it seems like the components and package directories are empty. Although these directories d ...