Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
JavaScript
document.getElementById("getForm").addEventListener("submit", (event) => {
    event.preventDefault();
    loadMovies(document.getElementById("input").value);
  });
  
  function loadMovies(name) {
    var omdbAPI = new XMLHttpRequest();
    var omdbURL = `http://www.omdbapi.com/?s=${name.replace(" ")}&type=movie&apikey=`;
    omdbAPI.open("get", omdbURL, true);
  
    omdbAPI.addEventListener("load", function()  {
  
      if (this.status == 200) {
        var result = JSON.parse(this.responseText);
  
        console.log(result);
  
        var output = "";
        for (var i = 0; i < result.lenght; i++) {
            output +=
            '<div class="movies">' +
            '<h3>Titel: ' + result[i].Title + '</h3>' +
            '<p>Year: ' + result[i].Year + '</p>' +
            '</div>';
            document.getElementById('result').innerHTML = output[i];
        }     
      } 
    })
    omdbAPI.send();
  };

HTML
<pre><form action="" method="get" id="getForm">
            <input type="text" name="query" id="input" placeholder="Search">
            <button type="submit">Search</button>
        </form>
        

        <div id="result">
            
        </div>



What I have tried:

I want the movies to display on the page when I search for a movie. In the console I get all the movies that contains "Grease" if I search for grease but nothing is displaying on the page in the
... What is wrong in my code?
Posted
Updated 7-Nov-21 22:24pm

1 solution

JavaScript
var output = "";
for (var i = 0; i < result.lenght; i++) {
    output +=
    '<div class="movies">' +
    '<h3>Titel: ' + result[i].Title + '</h3>' +
    '<p>Year: ' + result[i].Year + '</p>' +
    '</div>';
    document.getElementById('result').innerHTML = output[i];
}

You have declared output as a simple string, but you then try to add the first character ('<') to the result field in the web page. You should create a single div field and then add all the movie details one by one to the output variable. Then when you have completed the list you pass it to result.
JavaScript
var output = '<div class="movies">';
for (var i = 0; i < result.lenght; i++) {
    output +=
    '<h3>Titel: ' + result[i].Title + '</h3>' +
    '<p>Year: ' + result[i].Year + '</p>' +
}
output += '</div>';
document.getElementById('result').innerHTML = output;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900