Home > Software engineering >  Results not displayed in API call
Results not displayed in API call

Time:12-11

I am trying to call weather API, but for some reason I could not see the results both in console and the webpage after entering a specific city

I called

<div id="results"></div>

and made sure to declare it in my script. Can someone help?

Update: When I combine them into one file, the code works. But when I separate them into two different files, it does not work. What am I missing here?

This is the script.js of the code

var cityform = document.getElementById("cityform");
  
      // Check if the cityform variable is not null
      if (cityform !== null) {
        // Add a submit event listener to the form
        cityform.addEventListener("submit", function(event) {
          // Prevent the default form submission behavior
          event.preventDefault();
  
          // Get a reference to the input element
          var cityInput = document.getElementById("thecity");
  
          // Check if the cityInput variable is not null
          if (cityInput !== null) {
            // Get the input value
            var city = cityInput.value;
  
            // Make the API request using the city value
            $.getJSON("https://api.openweathermap.org/data/2.5/weather?q="   city   "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data){
  
            console.log(data);
  
              // Extract the data from the API response
              var icon = "http://openweathermap.org/img/w/"   data.weather[0].icon   ".png";
              var temp = Math.floor(data.main.temp)   "F"; 
              var weather = data.weather[0].main;
  
              // Get a reference to the element where the data will be displayed
              var results = document.getElementById("results");
              
              // Update the element with the data from the API
              results.innerHTML = "<img src='"   icon   "'> <p>"   weather   "</p> <p>"   temp   "</p>";
            });
          }
        });
      }
  

Then here is the HTML

<head>
    <meta charset="UTF-8">
    <meta name ="viewport" content="width=device=width, intial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content ="is=edge">
    <title>API</title>

    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

    <script src = "script.js"></script>
   

</head>

<body>
    <!-- HTML -->
<h1>Weather Report</h1>
<form id="cityform">
  <label for="thecity">City:</label><br>
  <input type="text" name="thecity" id="thecity"><br><br>
  <button type="submit">Search</button>
</form>

<!-- Create an element where the data will be displayed -->
<div id="results"></div>


</body>
</html>

What could be the possible issue or if there's no issue, how can you display the result of the icon, temp and weather to the "results"

CodePudding user response:

Paste the script.js linking part at the end. It might be possible that when your scripts is ran form was not creaded thus those variables were not existing that time.

See both example, this works

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device=width, intial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="is=edge">
        <title>API</title>
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
      </head>
      <body>
        <!-- HTML -->
        <h1>Weather Report</h1>
        <form id="cityform">
          <label for="thecity">City:</label>
          <br>
          <input type="text" name="thecity" id="thecity">
          <br>
          <br>
          <button type="submit">Search</button>
        </form>
        <!-- Create an element where the data will be displayed -->
        <div id="results"></div>
        
        <script>

          var cityform = document.getElementById("cityform");

          // Check if the cityform variable is not null
          if (cityform !== null) {
              // Add a submit event listener to the form
              cityform.addEventListener("submit", function(event) {
                  // Prevent the default form submission behavior
                  event.preventDefault();

                  // Get a reference to the input element
                  var cityInput = document.getElementById("thecity");

                  // Check if the cityInput variable is not null
                  if (cityInput !== null) {
                      // Get the input value
                      var city = cityInput.value;

                      // Make the API request using the city value
                      $.getJSON("https://api.openweathermap.org/data/2.5/weather?q="   city   "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data) {

                          console.log(data);

                          // Extract the data from the API response
                          var icon = "http://openweathermap.org/img/w/"   data.weather[0].icon   ".png";
                          var temp = Math.floor(data.main.temp)   "F";
                          var weather = data.weather[0].main;

                          // Get a reference to the element where the data will be displayed
                          var results = document.getElementById("results");

                          // Update the element with the data from the API
                          results.innerHTML = "<img src='"   icon   "'> <p>"   weather   "</p> <p>"   temp   "</p>";
                      });
                  }
              });
          }
          
        </script>
        
      </body>
    </html>

But not this

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device=width, intial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="is=edge">
        <title>API</title>
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

        <script>

          var cityform = document.getElementById("cityform");

          // Check if the cityform variable is not null
          if (cityform !== null) {
              // Add a submit event listener to the form
              cityform.addEventListener("submit", function(event) {
                  // Prevent the default form submission behavior
                  event.preventDefault();

                  // Get a reference to the input element
                  var cityInput = document.getElementById("thecity");

                  // Check if the cityInput variable is not null
                  if (cityInput !== null) {
                      // Get the input value
                      var city = cityInput.value;

                      // Make the API request using the city value
                      $.getJSON("https://api.openweathermap.org/data/2.5/weather?q="   city   "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data) {

                          console.log(data);

                          // Extract the data from the API response
                          var icon = "http://openweathermap.org/img/w/"   data.weather[0].icon   ".png";
                          var temp = Math.floor(data.main.temp)   "F";
                          var weather = data.weather[0].main;

                          // Get a reference to the element where the data will be displayed
                          var results = document.getElementById("results");

                          // Update the element with the data from the API
                          results.innerHTML = "<img src='"   icon   "'> <p>"   weather   "</p> <p>"   temp   "</p>";
                      });
                  }
              });
          }
          
        </script>

      </head>
      <body>
        <!-- HTML -->
        <h1>Weather Report</h1>
        <form id="cityform">
          <label for="thecity">City:</label>
          <br>
          <input type="text" name="thecity" id="thecity">
          <br>
          <br>
          <button type="submit">Search</button>
        </form>
        <!-- Create an element where the data will be displayed -->
        <div id="results"></div>
        

      </body>
    </html>

If you want to check yourself then just after var cityform = document.getElementById("cityform"); add alert(cityform)

When script linking is in head before body then we will get null in alert But when the script is at end near closing body tag then alert will have the form element.

Hope it helps. Comment if I am wrong somewhere.

CodePudding user response:

You need to move script from head location inside of body in HTML

This code works

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device=width, intial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="is=edge">
    <title>API</title>

    <script src="https://code.jquery.com/jquery-2.2.4.min.js"
        integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

</head>

<body>
    <!-- HTML -->
    <h1>Weather Report</h1>
    <form id="cityform">
        <label for="thecity">City:</label><br>
        <input type="text" name="thecity" id="thecity"><br><br>
        <button type="submit">Search</button>
    </form>

    <!-- Create an element where the data will be displayed -->
    <div id="results"></div>

    <script src="script.js"></script>

</body>

</html>
function resultSubmit(event) {
    event.preventDefault();
    // Get the input value
    var city = cityInput.value;

    // Make the API request using the city value
    $.getJSON("https://api.openweathermap.org/data/2.5/weather?q="   city   "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function (data) {

        console.log(data);

        // Extract the data from the API response
        var icon = "http://openweathermap.org/img/w/"   data.weather[0].icon   ".png";
        var temp = Math.floor(data.main.temp)   "F";
        var weather = data.weather[0].main;

        // Update the element with the data from the API
        results.innerHTML = "<img src='"   icon   "'> <p>"   weather   "</p> <p>"   temp   "</p>";
    });
}

const cityform = document.getElementById("cityform");
const cityInput = document.getElementById("thecity");
const results = document.getElementById('results')

cityform.addEventListener('submit', resultSubmit)

Result - I ran GO Live extension it in VS code

enter image description here

  • Related