Is there a way to extract information from my JSON file through the Google Books API URL and showcase it on my HTML page using JavaScript?

Seeking to retrieve volume information from the JSON array provided at this URL:

Desire to extract author, title, images, page numbers, and description.

The designated class in my HTML code where I intend to incorporate the mentioned JSON data is 'b-card' class:

    <div class="booklist">
        <div class="booklist-cards">
            <div class="b-card">

            </div>
            <div class="b-card">

            </div>
            <div class="b-card">

            </div>
            <div class="b-card">

            </div>
            <div class="b-card">

            </div>
            <div class="b-card">

            </div>
            <div class="b-card">

            </div>
            <div class="b-card">

            </div>
        </div>
    </div>

<script src="https://www.googleapis.com/books/v1/volumes?q=HTML5"></script>
<script src="assets/js/script.js"></script>

The script.js file content that I have attempted is as follows:

function handleResponse(obj) {

const book = Objects.keys(obj).map(item => obj['items']).reduce(
    (acc, rec, id, array) => {

    let singleBookCover = rec[id].volumeInfo.imageLinks.thumbnail;
    let singleBookTitle = rec[id].volumeInfo.title;
    let singleBookAuthor = rec[id].volumeInfo.authors[0];

    return [...acc, {singleBookCover, singleBookTitle, singleBookAuthor}]
    },
    []
).forEach( item => {
    let title = document.createElement('h1');
    title.textContent = `${item.singleBookTitle}`;

    let author = document.createElement('strong');
    author.textContent = `${item.singleBookAuthor}`;

    let img = document.createElement('img');
    img.src = item.singleBookCover;
    img.alt = `${item.singleTitle} by ${item.singleBookAuthor}`;

    let container = document.getElementsByClassName('b-card');

    container.appendChild(title).appendChild(author).appendChild(img);


})
return book
}

The above code currently only incorporates the title image and author, but fails to render them on my HTML. How can I troubleshoot this issue? Is the URL correctly called in the HTML script tag?

Note: Preferably aiming to resolve this without utilizing JQuery & AJAX. Also tried injecting the callback to handleResponse in the script tag URL unsuccessfully.

Answer №1

it's not possible to directly append to the HTML since container is an array and requires the index of the element

container[index].appendChild(title).appendChild(author).appendChild(img);

however, here's a simplified version with a reminder to include &callback=handleRespons in the API URL

function handleResponse(obj) {
   obj.items.forEach((item, index) => {
    if(index > 7) return; // limit 8 result
    let div = document.createElement('div');
    div.className = 'b-card';
    div.innerHTML = `<h1>${item.volumeInfo.title}</h1>
    <p><strong>${item.volumeInfo.authors[0]}</strong></p>
    <img src="${item.volumeInfo.imageLinks.thumbnail}" alt="${item.singleTitle} by ${item.volumeInfo.authors[0]}" />`
    
    let container = document.querySelector('.booklist-cards');
    container.append(div);
  })
}
<div class="booklist">
  <div class="booklist-cards">
  </div>
</div>
<script src="//www.googleapis.com/books/v1/volumes?q=HTML5&callback=handleResponse" async></script>

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

What is the reason behind the animation being refreshed when using slideToggle() in jQuery?

Recently, I managed to position a fixed div at the bottom of the viewport to serve as a contact tab. When this tab is clicked, it smoothly triggers a panel to slide out, which is functioning correctly. However, I'm faced with the challenge of making ...

AngularJS POST request encounters failure: Preflight response contains improperly formatted HTTP status code 404

I have encountered a persistent issue with microframeworks while attempting to perform a simple POST request. Despite trying multiple frameworks, none of them seem to handle the POST request properly: Here is an example using AngularJS on the client side: ...

Is there a way to execute a Node 6 npm package within a Node 5.6.0 environment?

I am currently utilizing a tool called easy-sauce to conduct cross-browser JavaScript tests. Essentially, my package.json file references this tool for the test command: { "scripts": { "test": "easy-sauce" } } Everything runs smoothly when I exec ...

Having issues with my jQuery getJSON request. It's returning an empty response even though

I have been struggling to find a solution to this particular issue with no luck... Here is the jQuery getJSON request that I am working on: $.getJSON("http://localhost:8080/context/json/removeEntity.html", { contentId : 1, entIndex : entityIndex ...

Best practices for working with HTML elements using JavaScript

What is the best approach for manipulating HTML controls? One way is to create HTML elements dynamically: var select = document.getElementById("MyList"); var options = ["1", "2", "3", "4", "5"]; for (var i = 0; i < options.length; i++) { var opt = ...

No Backend Detected for Tensorflow.js in Node

I've been attempting to develop a Discord bot that utilizes the @tensorflow-models/qna library, but I've hit a roadblock for the past 4 hours. Every time I run the script below: const qna = require('@tensorflow-models/qna'); (async () ...

What prevents me from changing the component's state while inside a useEffect callback?

I have been working on creating a timer that starts running when the app is in the background, and then checks if it has been 15 minutes (for testing purposes, I am using 15 seconds). If the time limit is crossed, the app logs the user out, otherwise, the ...

What steps can I take to avoid random divs from overlapping on smaller screens when dealing with elements created in the created() hook?

I encountered an issue with the code I'm working on (the circles overlap in the fiddle provided, but display correctly on my PC - possibly due to pixel discrepancies in the fiddle). You can find the code here. TestCircle.vue: <template> <d ...

Step-by-step guide on utilizing User scripts with the $window.open function in AngularJS

I am looking to initiate the following action - (for example: Upon clicking a button, it should direct to this , similar to how payment gateways function) and then, I need to input the user script below: getRealData('{"mailing":{"postalCode":"1 ...

Using the axios response to assign data object in VueJS

When making an API call, I am receiving an expected error. While I am able to log the error message in the console, I am encountering issues trying to set a vuejs data variable with the response. Can anyone point out what I might be doing incorrectly? ...

Include a new key and its corresponding value to an already existing key within FormData

I have a form that includes fields for title, name, and description. My goal is to submit the form values using an API. To achieve this, I am utilizing jQuery to add key-value pairs to the FormData variable: formdata.append('description_text', jq ...

information directed towards particular positions on a meter

I am in the process of creating a dashboard skin that receives data from a game via a plugin. I have encountered a problem with the RPM gauge. The issue is that the angle from 0 to 5 on the gauge is smaller than the angle from 5 to 10. I am attempting to s ...

Master the art of horizontal scrolling in React-Chartsjs-2

I recently created a bar chart using react.js and I need to find a way to enable horizontal scrolling on the x-axis as the number of values increases. The chart below displays daily search values inputted by users. With over 100 days worth of data already, ...

Retrieving Information from an API with Custom Headers in React Native

I have an API that necessitates specific headers for access. Without these headers, a browser displays the following error: Code: 4101 Message: Header X-Candy-Platform is required However, when the headers are provided, the API returns a json response. ...

Nested function unable to assign values to variables

I am currently working on a function in Discord.js that collects users who reacted to a message. I have managed to gather all the user IDs inside a nested function, but when trying to return the array to the caller, it does not seem to work as expected. He ...

Serialization using Newtonsoft.Json results in an empty JSON response

I have a list of objects from the following classes: public class Catagory { int catagoryId; string catagoryNameHindi; string catagoryNameEnglish; List<Object> subCatagories; public Catagory(int Id, string NameHindi, string NameE ...

Limits on zooming with THREE.js Orbit controls

I've encountered an interesting limit while using Orbit controls. The zooming functionality is tied to the radius of the spherical coordinates of the camera in relation to the orbiting axis. Here's how it functions: Whenever the user scrolls, t ...

AngularJS: Encountering an unexpected identifier while trying to make a POST

I'm facing an issue with my http POST request in AngularJS. When I make the function call to $http, I receive a SyntaxError: Unexpected identifier. The unexpected identifier is pointing to the line url: 'rating-add' within my $http call. ‘ ...

Expandable Grid with UI-GRID - Automatically expand a row when clicked on

I prefer not to utilize the default + icon for expanding the row. The row should expand when clicked anywhere on it. I attempted the following: HTML <div ui-grid="gridOptions" ui-grid-expandable class="grid"> Controller var app = angular.module( ...

How to print a specific div from an HTML page with custom dimensions

I am looking for a solution to print just a specific div from a website with dimensions of 3"x5". Despite setting up the print button, the entire page continues to print every time. Is there a way to hide all non-div content in print preview? CSS .wholeb ...