Leveraging AJAX for fetching weather data from OpenWeather API with JavaScript

I'm facing an issue while creating a basic HTML page that fetches data from the OpenWeather API using AJAX. The problem lies in my latitude and longitude parameters not being correctly inserted into the URL. I've been trying to identify the mistake, but haven't had any luck so far.

My JavaScript Code:

var request = new XMLHttpRequest();

    function getWeather() {
        var latitude = document.getElementById("lat").value;
        var longitude = document.getElementById("long").value;
        request.open('GET', 'https://openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&appid=547fa6dfa44cff13fa92bba2c465b366', true); 
        request.send();
        request.onreadystatechange = displayData;
    }


    function displayData() {
        if(request.readyState === 4 && request.status === 200) {
           var resultData = JSON.parse(request.responseText);
           var temperature = document.getElementById("temperature");
           var windspeed = document.getElementById("windspeed");
           temperature.value = resultData.main.temp;
           windspeed.value = resultData.wind.speed;
           document.getElementById("resultset").style.visibility = "visible";
        }
     }

     window.onload = function() {
         var btn = document.getElementById("btn");
         btn.addEventListener("click", getWeather, false);
    }

My HTML Code:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta id="viewport" content="width=device-width, initial-scale=1.0">
   <link rel="stylesheet" href="css/styles.css" />
</head>

<body>
   <header>
      <h1>Weather Report</h1>
   </header>
   <article>
      <h2>Weather Data</h2>

         <form action="#" method="post" id="theForm" novalidate>
         <fieldset id="zipset">
            <label for="lat" id="lat">Latitude:</label>
            <input id="lat" type="number" />
            <label for="long" id="long">Longitude</label>
            <input id="long" type="number" />
         </fieldset>
         <fieldset id="resultset">
            <label for="temperature" id="temperature">Temperature:</label>
            <input id="temperature" type="text" />
            <label for="windspeed" id="windspeed">Wind Speed:</label>
            <input id="windspeed" type="text" />
         </fieldset> 
         </form>
       <button id="btn">Submit Coordinates</button>
   </article>
   <script src="js/weather_report1.js"></script>
</body>

Answer №1

There doesn't appear to be any element with the ID "zip", as well as for city and state. It seems like multiple elements have been assigned the same ID, which can cause issues. Additionally, attributes such as latitude, longitude, temperature, and wind speed are being duplicated, which is not best practice.

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

Switching between height: 0 and height:auto dynamically with the power of JavaScript and VueJS

Currently, I am changing the height of a container from 0px to auto. Since I do not know the exact final height needed for the container, using max-height could be an option but I prefer this method. The transition from 0 to auto works smoothly, however, ...

Encountering a 500 server error when using jQuery AJAX for a GET request

Check out the flask python code here: Also, take a look at the html+js in the index.html template: An issue arises where everything runs smoothly on the local Flask server but encounters a 500 error when attempting to search after deployment with Apache ...

Getting the first array from a fetch promise is a process that involves accessing the

When working with a fetch promise, I need to return a JSON object that contains all of my data. The challenge is that I am not sure what the object name will be. What I do know is that there will always be one object present. Below is an example of my cod ...

Adjust form elements dynamically depending on the selected option in a dropdown menu using Ruby on Rails

I currently have the following database tables set up: Departments ID| Department_name | Manager_ID Employees ID| Name | Department_ID Salaries ID| Employee_ID | Salary_Amount The departments table holds information about different departments within t ...

Executing PHP function through AJAX

I have thoroughly researched various resources regarding my issue but still have not been able to find a solution. My goal is to retrieve the result of a PHP function using jQuery AJAX. function fetch_select(){ val_name = $('#name').val(); ...

Differences between WebSockets protocol and HTTP

Many blogs and discussions focus on the comparison between WebSocket and HTTP, with developers and websites advocating strongly for WebSockets. However, the reasons for this preference are not always clear to me. Here are some arguments in favor of WebSoc ...

Utilizing an HTML time picker for scheduling specific time intervals

Is it possible to use an HTML time picker with a specific interval? https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time According to the link, the step attribute is supported, but I have tested it on the latest versions of Chrome, Edge, ...

Guide on setting up a new NPM and JavaScript project within Visual Studio 2015

Whenever I watch tutorials, they always mention having a "special npm reference" that I seem to be missing. https://i.sstatic.net/I52dn.png All I can find are the "normal" references (.net assemblies). I also can't locate any project type labeled as ...

Tips for efficiently showcasing array responses in Vue.js and Laravel

I am looking to showcase array data within a .vue file, but I am uncertain about the process. This is my attempt: <template> <div id="app"> <table class="table table-striped"> <thead> <tr> ...

Omit specific object properties within a foreach loop in jQuery AJAX

Check Out This Fiddle Example I am currently working with a PHP file that returns JSON data for main content along with an additional property for pagination. I am looking for a way to exclude the pagination property when iterating over the data in a fore ...

Excessive form inputs extend beyond the modal when utilizing Bootstrap 3

Having an issue loading a modal with Angular and populating it with a template. The main problem I'm facing is that the inputs are extending beyond the boundaries of the modal - attached below is a screenshot illustrating the problem: Below is the c ...

The $scope in Angular doesn't seem to be working as expected in the callback function, despite using $scope

I'm currently working on converting the JSFiddle found here to AngularJS: http://jsfiddle.net/danlec/nNesx/ Here is my attempt in JSFiddle: http://jsfiddle.net/leighboone/U3pVM/11279/ var onAuthorize = function () { updateLoggedIn(); $scope. ...

Adjust the size of an array based on the specified index

I have an array defined as... let myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] ...along with a starting index let start = 2 and an ending index let end = 5. I want to resize the array by taking elements from start to end, for example: start ...

The reason behind the successful execution of the final .then in promise chaining

I am new to JavaScript and have encountered an interesting problem with the following code. Even though I haven't returned anything from the .then method, the last .then (blue color) works instead of the first one (red color). Can someone explain why ...

The most efficient method for searching and deleting elements from an array in Mongoose

I'm currently struggling with my implementation of mongoose in express. It seems like I'm using too many queries just to add something to a document, and I can't help but feel that there's a simpler way to achieve this. This function i ...

Searching through an array to isolate only image files

I am working with an array that contains various file types, all stored under the property array.contentType. I am trying to filter out just the images using array.contentType.images, I believe. Check out the code snippet below: const renderSlides = a ...

Ajax Live Search Error Detected

Having trouble retrieving data from the database..! <html> <head> <title>Live Search</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> &l ...

Changing the default download directory in Selenium using JavaScript

How can I use JavaScript to change the default download directory? I have a list of folders and one is named "C:\Study\Selenium". How do I update the location for downloaded files to this specific path in my code? chromeOptions.setUserPreference ...

How can I trigger a method after the user has finished selecting items in a v-autocomplete with multiple selection using Vuetify?

After multiple selections are made in a v-autocomplete, I need to trigger a method. However, the @input and @change events fire after each selection, not after the full batch of selections. Is there an event that triggers when the dropdown menu closes? Al ...

Is it possible to customize the CSS styles of a jQuery UI modal dialog box?

Having trouble with my CSS styles not applying to a dialog modal added to my website using jQuery UI, even when using '!important'. I suspect that the predefined jQuery or UI CSS styles from a CDN link are preventing me from overriding them. The ...