Home > Back-end >  How to send data from API to another HTML file
How to send data from API to another HTML file

Time:12-03

Im using a TMDB API to search for movies and add them to a watchlist.

In this javascript function im getting movie details based on user input and rendering the results to html using bootstrap.

const searchMovie =  async (searchInput) => {
    try { 
      axios.get(`https://api.themoviedb.org/3/search/movie?api_key={API_KEY}&language=en-US&query=${searchInput}&page=1&include_adult=false `)
      .then((response) => {
        console.log(response);
        let movies = response.data.results;
        let displayMovies = '';
        $.each(movies, (index, movie) => {
          displayMovies  = `
          <div >
          <div >
          <a href="https://www.themoviedb.org/movie/${movie.movie_id} target="_blank"><img src="https://image.tmdb.org/t/p/original${movie.poster_path}"></a>
            <h5>${movie.title}</h5>
            <h4>${movie.release_date}<h4>
            <a  href="#">Add to watchlist</a>
          </div>
        </div>
          `;
        });
        
        $('#movies').html(displayMovies);
      })
    }catch(error) {
     console.log(error)
    }
}

I have another html file called watchlist.html that i want to send the movie selected from the search results to that file and build a watchlist.

CodePudding user response:

To send data from one HTML file to another, you can use the localStorage or sessionStorage objects available in JavaScript. These objects allow you to save key-value pairs of data in the user's web browser, which can be accessed on the same domain by other pages.

Here's an example of how you could use the localStorage object to save the data in the first HTML file and access it in the second HTML file:

First HTML file (search results):

// Save the movie data in localStorage when the "Add to watchlist" button is clicked
$('#add-to-watchlist-button').on('click', () => {
  let movie = {
    title: movie.title,
    releaseDate: movie.release_date,
    // Other movie data
  };

  localStorage.setItem('selectedMovie', JSON.stringify(movie));
});

Second HTML file (watchlist):

// Retrieve the selected movie from localStorage and display it on the page
let selectedMovie = JSON.parse(localStorage.getItem('selectedMovie'));
if (selectedMovie) {
  // Display the selected movie on the page
}

Remember to call localStorage.removeItem('selectedMovie') or localStorage.clear() when you no longer need the data, to free up space in the user's browser.

CodePudding user response:

Please try this one before stringify

var obj = JSON.parse(movie);
localStorage.setItem('selectedMovie', JSON.stringify(obj));
  • Related