Retrieve specific JSON elements and showcase on an HTML webpage

I created a simple webpage where users can input the name of an actor and I want to show all the movies that actor has been in. Currently, I have hardcoded the API URL for Bradley Cooper.

How can I retrieve all movie titles, release years, overviews, and poster images and display them on the page? Right now, I'm only showing one movie and it's not even the first one in the JSON file.

I believe I need to transform the JSON data into an array but I'm unsure how to do that and then showcase more than one result on the page.

Your assistance and guidance are greatly appreciated.

<!DOCTYPE html>
<html>

<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body onload="search_actor()">

<script>

  function search_actor() {

  $.getJSON({

    url: 'https://api.themoviedb.org/3/person/51329/movie_credits?api_key=f1d314280284e94ff7d1feeed7d44fdf',
    dataType: 'json',
    type: 'get',
    cache: false,
    success: function(data) {
        $(data.cast).each(function(index, moviedata) {

        // Movie Title
        document.getElementById("movietitle").innerHTML = moviedata.title;

        // Release Year
        document.getElementById("releaseyear").innerHTML = moviedata.release_date.substr(0, 4);

        // Movie Overview
        document.getElementById("movieoverview").innerHTML = moviedata.overview;

        // Movie Poster
        var fullmovieposterpath = '<img src=https://image.tmdb.org/t/p/w500/' + moviedata.poster_path + ' width="20%" height="20%">';
        document.getElementById("displaymovieposter").innerHTML = fullmovieposterpath;

        });
       }
     });
     }

</script>

<div id="movietitle"></div>
<div id="releaseyear"></div>
<div id="movieoverview"></div>
<div id="displaymovieposter"></div>
</body>
</html>

Answer №1

Within your code, there is a single container designated to display the movie items. It would be beneficial to iterate through the response and dynamically generate the movie cards. Utilizing a CSS grid system can provide greater control over the layout and placement of these movie cards.

$.getJSON({
  url: 'https://api.themoviedb.org/3/person/51329/movie_credits?api_key=f1d314280284e94ff7d1feeed7d44fdf',
  dataType: 'json',
  type: 'get',
  cache: false,
  success: function (data) {
    console.log(data)
    let k = '';
    data.cast.forEach(function (item) {
    //Using template literal to create a movie card
      k += `<div class='movie-card'>
              <div>${item.original_title}</div>
               <div><img src = 'https://image.tmdb.org/t/p/w500/${item.poster_path}'></div>
               <div><span>${item.release_date}</span></div>
               <div class='movie-desc'>${item.overview}</div>
              </div>`
    })
    $('.movie-conatiner').append(k)

  }
});

You can view a complete working version by visiting this link on StackBlitz

Answer №2

To prevent data overwriting, it is necessary to dynamically create divisions for each statement and then merge the data on the home page.

Ensure that only a single div is created in the HTML section with the ID "main".

Below you will find the modified code incorporating the aforementioned changes along with CSS styles for the divisions.

Code after receiving JSON response:

divcnt=1;

    divdata="";

    $(data.cast).each(function(index, moviedata) {          

         var fullmovieposterpath = '<img src=https://image.tmdb.org/t/p/w500/' + moviedata.poster_path + ' width="20%" height="20%">';

       divdata += '<div id="test'+ divcnt +'"><div id="movietitle'+ divcnt +'">'+moviedata.title+'</div><div id="releaseyear'+ divcnt +'">'+moviedata.release_date.substr(0, 4)+'</div><div id="movieoverview'+ divcnt +'">'+moviedata.overview+'</div><div id="displaymovieposter'+ divcnt +'">'+fullmovieposterpath+'</div></div>';

    });

      document.getElementById("main").innerHTML = divdata;

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

Encountering a Lerna success error message: "No packages were detected containing the lifecycle script 'typecheck'."

I'm encountering an issue when trying to start lerna. The error message I receive is 'lerna success run No packages found with the lifecycle script 'typecheck'. How can I resolve this? Here's a snippet from my package.json file: { ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...

Determining when the clear button is clicked in a v-select (vue-select) detection strategy

While working on creating a drop-down using v-select, I encountered an issue. After selecting an option, I needed to clear the drop-down and revert the option array back to its initial stage upon clicking the clear button. I attempted various methods such ...

Node.js alternative for PHP include in markup

Looking for a way to include PHP functionality in NodeJS/Express markup without using a full template engine like jade? Check out this interesting question: Nodejs Include Other Views? I'm in need of similar functionality, but I'm not keen on le ...

Utilizing JSON to organize arrays in a sorted manner

I am in need of a proficient JSON specialist or someone well-versed in JSON. Recently, I received a JSON structure from an API through an http request. The API arranges the data based on itemDistance, as per my query. However, when I process the data using ...

Exploring the world of HighCharts

I am trying to use Highcharts to calculate and visualize the magnitude of a complex number. Currently, my code is displaying the real and imaginary values separately on the graph. However, I seem to be facing issues with the "For loop" that I implemented ...

Create a Java class specifically for handling JSON data where the keys do not have consistent names but can have various values

Seeking guidance on how to model a JSON file in Java, specifically for the Jackson library. The challenge is that the key in the JSON file represents the file name and is not constant. { "core/core-rwd/src/scss/_colors.scss": [ { "line": 1, ...

How can I get electron to interact with sqlite3 databases?

I've exhausted all my options and still can't get it to function. This error message keeps popping up: https://i.stack.imgur.com/D5Oyn.png { "name": "test", "version": "1.0.0", "description": "test", "main": "main.js", "scripts": { ...

Accessing JSON output to retrieve data from an Asterix file

Looking to convert a radar data file, provided in JSON format, into a usable DataFrame structure. The initial three lines of the file present as follows: {"id":1,"length":43,"crc":"D81B2DB5","timestamp":16 ...

JSON: A guide on transforming a flat JSON structure into a nested one

I've been struggling to transform a rather flat JSON structure into one with more depth, but I haven't had any luck so far. Here is the initial data: [ { "id": "27", "time": "2017-12-21 07:24:00", "service_name": "prices", "vers ...

Opting for frontend technologies such as React or Angular to update a Silverlight application containing over 1000 unique forms and views

We are in the process of transitioning our Silverlight application to modern web technologies like React or Angular due to the impending end of life for Silverlight by the end of this year. We are seeking advice on selecting the most suitable frontend tec ...

Is it possible to verify an email address using a "Stealthy Form"?

I am exploring the use of HTML5's type="email" validation to develop a function for validating email addresses. My goal is to create a form and add an input that has its type set as email. By attempting to submit the form, I aim to determine whether ...

Exploring the mechanics of JavaScript and jQuery Ajax: What's the secret to its function

It's common knowledge that browsers are single-threaded, meaning they can only either render the UI or execute Javascript snippets. While web workers offer a way to achieve multi-threading, let's focus on the default behavior. I'm curious a ...

using the information from the child array within a v-if condition

I'm struggling to extract data from a child array and utilize it in my v-if condition. Below are my data and code. Any assistance would be appreciated, even if it's just pointers to the right documentation. <div class='post' v-for= ...

Detecting changes in Angular from the parent to the child component can be accomplished by utilizing a specific approach

The Sample Component contains data in the form of an array of objects with child components within a loop. Sample.component export class SampleComponent implements OnInit { data = [{ value: 3 }, { value: 1 }]; constructor() {} ngOnInit(): void {} ...

What is the method for retrieving a JSON data array using PHP/Laravel?

Currently, I am working on developing an API using Laravel and my task involves retrieving data from a JSON file located at a specific URL. Below is the code snippet I have written for this purpose: public function index(){ $json_file=file_get_contents ...

Using react-input-mask together with a child component in React is not compatible

I've been exploring ways to mask a Material UI TextField, and after researching some solutions online, I came across this code snippet: <InputMask mask="(0)999 999 99 99" value={phone} disabled={false} ...

Struggling with transferring a JavaScript array to the current page using AJAX

This might sound like a common question, but I have conducted thorough research and none of the solutions provided have worked for me. I have a javascript array structured as follows: [from: "2016-04-01", to: "2016-04-14"] I am sending this array via AJA ...

Managing multiple promises with multiple steps

I am looking to extract information from various sources. Once each dataset is obtained, I want to send it to a separate asynchronous processor such as a worker thread. After all processes are complete, I aim to combine the data and deliver it. Here is an ...

Requirement for mobile browser support in creating object URLs - must use the URL prefixed as webkitURL."

After digging into the MDN web docs for createObjectURL (https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL), it's clear that when looking at Browser Compatibility (mobile), this method is specifically supported by certain mobile bro ...