Exploring the Unsplash API: Using JSON Data to Populate an HTML Display!

I can't seem to display the JSON data I fetched on my HTML webpage. The data is coming in correctly, but for some reason, it's not showing up. There might be an issue with how I'm handling the objects and arrays.

Any help would be appreciated.

const API_URL = 'https://api.unsplash.com/search/photos?page=1&client_id=00000000000';
const form = document.querySelector('form');
const input = document.querySelector('input');

const loadingImage = document.querySelector('#loadingImage');
const imageSection = document.querySelector('.image');

loadingImage.style.display = 'none';

form.addEventListener('submit', formSubmitted);

function formSubmitted(event) {
    event.preventDefault();
    const searchTerm = input.value;

    searchStart();
    search(searchTerm)
        .then(displayImages)
        .then(() => {
            loadingImage.style.display = 'none';
        });
}

function searchStart() {
    loadingImage.style.display = '';
    imageSection.innerHTML = '';
}

function search(searchTerm) {
    const url = `${API_URL}&query=${searchTerm}`;
    loadingImage.style.display ='';
    return fetch(url)
        .then(function(response) {
            return response.json();
        });
}


 function displayImages (images) {
      images.forEach(results => {
          const imageElement = document.createElement('img');
          imageElement.src = results[0].urls.full;
          imageSection.appendChild(imageElement);
      });
  }

Example response

{
  "total": 8083,
  "total_pages": 809,
  "results": [
    {
      "id": "qY9zgRqmNtA",
      "created_at": "2018-03-27T11:42:54-04:00",
      "updated_at": "2018-08-28T20:56:16-04:00",
      "width": 6435,
      "height": 4290,
      "color": "#FCFDFD",
      "description": "people working inside white and black room",
      "urls": {
        "raw": "https://images.unsplash.com/photo-1522165078649-823cf4dbaf46?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjM4NDEyfQ&s=7d8696c868ca2cea4d2b337d0f42f6c1",

Answer №1

After examining the data's format, it is clear that modifications are needed for the displayImages function.

Although I cannot confirm the existence of a property named full in each entry, I am assuming its presence based on the original code. Providing an actual example of the data within the question would simplify this process.

function displayImages(result) {
      result.results.forEach(img => {
          const imageElement = document.createElement('img');
          imageElement.src = img.urls.full; // Is 'full' present?
          imageSection.appendChild(imageElement);
      });
  }

Answer №2

{
  "total": 8083,
  "total_pages": 809,
  "results": [
    {
      "id": "qY9zgRqmNtA",
      "created_at": "2018-03-27T11:42:54-04:00",
      "updated_at": "2018-08-28T20:56:16-04:00",
      "width": 6435,
      "height": 4290,
      "color": "#FCFDFD",
      "description": "people engaging in tasks in a monochrome room",
      "urls": {
        "raw": "https://images.unsplash.com/photo-1522165078649-823cf4dbaf46?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjM4NDEyfQ&s=7d8696c868ca2cea4d2b337d0f42f6c1",

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

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

Exploring the capabilities of Angular functions through JavaScript and jQuery

As a coding novice, I'm unsure which language this is. The component.ts file I have contains a function that I need to access outside of ngOnInit(). I tried using this.openDialog(), but it came up as undefined. I attempted defining the function in Ja ...

Implementing dynamic attribute id addition to select option

Here's the code snippet I'm currently working with: Included HTML <select id="drop_opts"> <option>1<option> <option>2<option> <option>3<option> </select> ...

Validation of minimum and maximum character length using jQuery

I am trying to implement a validation that requires a minimum length of 8 and a maximum length of 14 characters. Can anyone guide me on how to achieve this? Here is the code snippet in HTML: <input type="text" name="354" id="field"> And here is th ...

"Encountering an issue while using Node.js to spawn Python for processing binary images, receiving the error message 'node error spawn ENAMETOOLONG'

My current issue involves trying to save an image by initiating a python process from within a node.js script. This image is transmitted as binary data from the Node.JS script to the Python process. In my index.js script, I spawn a python script named my_ ...

The parameter is returning undefined, while the PHP select by ID is returning null

Can someone please assist me with this issue? I am trying to select and update data by id from a SQL database, but I am not getting the expected result. The PHP file is returning null. Upon checking in my developer tools, I noticed that the parameter code ...

What causes unescaped HTML characters to become unescaped when using $('div :not(script)').contents().filter(function()?

Developing a Chrome Extension that utilizes a click-to-call API, I have encountered an issue where certain pages are displaying unusual behavior. After investigating, I have identified this specific code snippet as the source of the problem. var rxpCtc = n ...

Tips for making a JSON object with a variable amount of properties

I am looking to transform a structure similar to the following: List<String> fields; into JSON format like this: { "field1": "data1", "field2": "data2", "field3": "data3", ... } ...

Unable to interpret the JSON reply from the server

I am currently developing a web application that sends data to a website, which then updates its database and returns a JSON array to replace my web app page. I am using AJAX for this query, but I am facing an issue with preventing the overwriting of my we ...

Retrieving information from Node.js Serialport

I am interested in reading the data received after sending an ascii command to my lock controller. Here is the code that sends the command to the lock controller: var express = require('express'); var router = express.Router(); var SerialPort = ...

Is ASP.NET's web-based chat system effective with Ajax timers for handling a high volume of users?

It is common knowledge that a basic chat can be created using an ajax timer and web service, functioning adequately for a small number of users. I am considering using the same concept for a site with over 5000 users in a chat room. Messages would be stor ...

notification that appears when checkbox is ticked

If a certain delivery option is selected during the checkout process on our website, we would like to trigger a popup box displaying a custom message. Here is the specific checkbox for that delivery option: <input id="delivery_option_22_6" class="deliv ...

Browse through all products with just one click using JQuery!

I am trying to achieve a feature where clicking a 'View all' button under the product sheets will display all the products in alphabetical order by adding clones at the bottom of the page to fill all available spaces. Can you assist me with this? ...

Variances in errors observed while accessing a website on ports 80 and 5500

I've been developing a chatbot system, and I'm encountering an issue where I receive an error message every time I send a message and expect a response back. What's puzzling is that the error message varies depending on whether I run the si ...

Navigating through directories (including nested ones) containing images in React Native; what's the best way to approach this

I am currently attempting to organize groups of images. Within the directory ./assets, there are several folders structured as follows: ./assets ├── 1x3 │ ├── 1.jpg │ ├── 2.jpg │ └── 3.jpg └── 3x3 ├── 1. ...

The content in an app using Ionic and Angular is being obstructed by the bottom tabs, preventing users

I am facing an issue with my Ionic and Angular app. When I place tabs at the bottom of my page, outside the ion-content, the scrolling stops working inside the ion-content and the fab button, which is located inside the ion-content, ends up covering the ta ...

Switching XML to JSON using Python while confirming it against a schema

I am looking for a solution to convert XMLs into JSON format. Although I have found various packages like xmltodict in Python that can accomplish this, I'm facing an issue where single elements within a node are being converted into dictionaries. Howe ...

Aurelia's navigation feature adds "?id=5" to the URL instead of "/5"

I have set up my Aurelia Router in app.ts using the configureRouter function like this: configureRouter(config, router: Router) { config.map([ { route: ['users', 'users/:userId?'], na ...

Adding new information to MongoDB

Greetings to all the wonderful users of stackoverflow! I'm currently encountering an issue involving mongodb and nodejs. I'm attempting to insert data into mongodb, and I have all the necessary data ready in a csv file format. Here's a brie ...

The $interval cancellation in AngularJS is not functioning as expected, and neither the onDestroy nor stateChangeSuccess events are working as

Below is a snippet of code I wrote to set up an interval that should be canceled when leaving the state, but it's not working as expected. var init = function () { $translatePartialLoader.addPart("app/bottling/palletTnT/palletTnT.grid"); ...