What is the best way to show an image within a div using HTML and fetching data from an API response?

I am attempting to showcase an image within a div using HTML. I utilized fetch to retrieve the JSON data from the following API: . The response contains JSON data with the image URL labeled "primaryImage". While I can display it as text, I am encountering difficulties displaying it as an image.

<!DOCTYPE html>
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<title>Image</title> 
</head> 

<body> 
<img id="test">

<script>


    let getimage = document.getElementbyId('test');
    getimage.src= "data"

    fetch('https://collectionapi.metmuseum.org/public/collection/v1/objects/435828')
    .then((response) => response.json())
    .then((data) => texting.innerText = data.primaryImage);

</script> 
</body> 
</html>

Answer №1

When updating your sample page,

make the following substitution;

.then(data => getimage.src = data.primaryImage);

Answer №2

To simplify the process, you can follow these steps:

  • Store your image in a variable for easy access later on.
  • Send a request to your API.
  • Parse the API response as JSON.
  • Update the source of the image, specifically the src attribute, with the value from the primaryImage field in the API response.

For a visual demonstration, here is an example:

// Store the image element for later access
const img = document.getElementById('example');

// Send a request to the API
fetch('https://api.example.com/data')
// Parse the JSON response
.then(response => response.json())
// Update the image's source with the API data
.then(data => img.src = data.primaryImage);
<img id="example">

If needed, consider adding a loading indicator while the image loads. However, it's beyond the scope of this answer to delve into that aspect.

Keep in mind that APIs vary and their response formats can change. Nevertheless, the general process remains similar in most cases.

I suggest exploring the Fetch API documentation to understand its functionality better.

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

Error: The variable "email" is not defined

Hey there, I could really use some assistance as a struggling developer. I've been at it all day trying to resolve this issue with no luck. It should be a simple task of posting from my AddUsers class and storing it in my SQL database. The state upda ...

Is there a way to launch my JavaScript project locally and have index.html served on an npm server?

I am currently attempting to launch a specific Single Page Application (SPA) project using pure JavaScript. This project consists of a script file and an index.html file. I am trying to run this project on my local machine, but it requires that it be hos ...

Leveraging JavaScript within a Polymer component

I have an object made with polymer: <newfolder-element id="newfolderelement" popupStyle="width: 362px; height: 100px;"> <span class="title">Create a new folder</span> <input type="text" class="ginput" style="width: 350px; padd ...

Strategies for making a child div fade out when the parent div is hovered over

I have a div with the class name ordershape and inside it, there is another div called fad-res. My goal is to display the corresponding fad-res when I hover over a specific ordershape, while hiding the other divs. <div class="ordershape"> & ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Is there a way to sort data by year and month in mongodb?

I'm trying to filter data by year in MongoDB based on a specific year and month. For example, if I pass in the year 2022, I only want to see data from that year. However, when I try using the $gte and $lte tags, it returns empty results. Can someone g ...

Having difficulty retrieving JSON data using Jquery

After receiving a JSON string as a response from the server, I encountered an issue when trying to access the objects within the response, only to receive an "undefined" message. Here is the AJAX request being made: $.ajax({ url: 'somefi ...

A guide on invoking a web method from an aspx.vb page in VB.net

My goal is to call a WebMethod from my aspx.vb file. Below is the syntax of my WebMethod located in Default.aspx.vb: <System.Web.Services.WebMethod()> _ <ScriptMethod(UseHttpGet:=True, ResponseFormat=ResponseFormat.Json)> _ Public Shared Funct ...

Implement ajax functionality to update an object within a JSP page

On my JSP page, I have implemented an accordion list (utilizing Bootstrap 3) with text and a Delete button within each node. When the user clicks on the delete button, that specific list item is removed. To construct the accordion list, I bring in an Array ...

Creating a new music application and looking for ways to keep track of and update the number of plays for

I'm currently developing a music app and am looking for a way to update the play count every time a user listens to a song for at least 30 seconds. I've attempted the following approach: let current_final; let current_initial; ...

Unable to retrieve dropdown value using JavaScript and display it in a div

javaScript code: Retrieving data from a dropdown and displaying it in the inner HTML of a div. function showcost() { var days = document.getElementById("Ddays"); var Dudays = days.options[days.selectedIndex].text; var div = docu ...

Troubleshooting a malfunctioning Highcharts yAxis maximum setting

Can someone explain why the yAxis is still labeled up to 15 when the max value is set to 14? I've tried adjusting the startOnTick and maxPadding properties with no success. Here's the link to the code. $(function () { $('#container&apo ...

Restrict access to table records by specifying an array of row identifiers

Hi everyone, I've encountered a small issue. Just to provide some background, I have a table with checkboxes. Each row in the table has an associated ID, and when selected, I receive an array like this: const mySelectedRoles = [1997, 1998, 1999] Once ...

Is there a way to refresh a table view while in a class?

When I click the update status button, I want to reload the table view on InquiryViewController. The update status button fetches JSON data containing the status of a message. The code snippet is as follows: -(BOOL)getMessageStatus : (NSMutableArray *)em ...

Unable to retrieve information for PayPal v2 Order generated on client side

My website features a membership option spread across 3 pages, each serving a specific purpose - one for presenting the membership along with a PayPal button, another for member registration into the database, and the last to inform users that they can now ...

The CSS background and background-image are visible exclusively on the Chrome desktop browser

Why is the background image not showing up on my website? The img src is also not displaying. All pictures show up fine on Chrome desktop browser, but not on Chrome mobile browser. Other browsers that are not displaying the images include Safari mobile, I ...

Customize stepper background color in Angular Material based on specific conditions

I am working on a project using Angular Material and I want to dynamically change the color of the stepper based on different states. For example: state: OK (should be green) state: REFUSED (should be red) Here is what I have done so far: <mat-horizo ...

Utilize jQuery to showcase elements in a dropdown menu

Hey everyone, I'm working on an ASP.NET MVC4 project and I'm using a jQuery script on the edit page. However, I am encountering an issue with displaying elements on the page. Here is the initial HTML markup of my dropdown before any changes: & ...

Utilizing AJAX to fetch API data and leveraging jQuery to iterate through intricately nested JSON data structures

I've implemented AJAX to connect to an API that returns a JSON object (see the JSON code reference below) and I'm trying to iterate through and parse the JSON data to display inside an HTML element. Although everything else in my code is functio ...

HTML elements are replaced by codes on the screen

After setting up an ajax request to run at regular intervals, I encountered a problem when trying to navigate back. Instead of displaying the expected HTML elements, the browser showed all of my HTML code. <script> window.setInterval(function () ...