Utilizing user input to execute an API request

I am working with a form that allows the user to input a city name. I want to use an API call to retrieve weather data for that specific city and display it in the console.

Unfortunately, I'm encountering an error where the variable containing the input value is not being properly concatenated into the string.

Below is the code snippet:


var request;
var input1 = document.getElementById('city');
var api = 'https://api.openweathermap.org/data/2.5/weather?q=';
var apikey = '&APPID=433b12b793d7ebc17989745c069a540b';
var sum = api + input1.value + apikey;

function myFunction() {
  request = new XMLHttpRequest();
  
  request.open('GET', sum, true);
  request.onload = function() {

    var data = JSON.parse(this.response);
    if (request.status >= 200 && request.status < 400) {
      console.log(data);
    } else {
      console.log(input1.value);
    }
  }

  request.send();
}
myFunction(input1.value);
<input id='city' value='San Francisco'>

Any assistance would be greatly appreciated!

Answer №1

Your code appears to be correct, but make sure to encapsulate everything within the function.

 <script>
    function checkWeather() {

        var request;
        var cityInput = document.getElementById('city');
        var apiUrl = 'https://api.openweathermap.org/data/2.5/weather?q=';
        var apiKey =
            '&APPID=433b12b793d7ebc17989745c069a540b';
        var url = apiUrl + cityInput.value + apiKey;

        request = new XMLHttpRequest();

        request.open('GET', url, true);
        request.onload = function () {

            var weatherData = JSON.parse(this.response);
            if (request.status >= 200 && request.status < 400) {
                console.log(weatherData);
            } else {
                console.log(cityInput.value);
            }
        }

        request.send();
    }
</script>

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

Automatically bring in functions in JavaScript without explicitly declaring them

I am working with 2 files. //main.js const one = (text) => { return text; } const two = (text) => { return text + " is here"; } module.exports = [ one, two ] //app.js const data = require("./main.js"); console.log(data.one("exampl ...

Using arrays as data in an Ajax request for DataTables

Struggling to send selected row IDs to an API using the DataTables Ajax option. Despite numerous attempts, I can't seem to get the IDs sent as an array. Below is a sample code I've tried. It generates the URL: getStatistics.php?ids=1&ids=2& ...

Hold off on advancing until the particular text is found in the DOM element

One of the challenges I'm facing is creating a function that waits for specific text to change before returning a value: function getElementText() { while(isLoading()) { } return $('#element').text(); } function isLoading() { ...

Bootstrap: The search icon button within the input box breaks away from the input box on resolutions other than desktop

I am attempting to place a Search Icon Button inside the Search Input Box while using Bootstrap. Although everything appears correctly at Desktop resolution, at non-desktop resolutions when the menu items collapse into a dropdown, the button and input box ...

Identification of input change on any input or select field within the current modal using JavaScript

My modal contains approximately 20 input and select fields that need to be filled out by the user. I want to implement a JavaScript function to quickly check if each field is empty when the user navigates away or makes changes. However, I don't want t ...

Using jQuery to Organize JSON Tables

I'm in a bit of a bind... I'm in need of sorting tables from a list of formulas. I've extracted 3 parameters from JSON files and created formulas, but now I need to sort this list of formulas. JSON files: <body> <script> $ ...

Guide to showcasing user input using a Javascript function

I need assistance to show the user input via the submit button. Users will enter tool types and the first five inputs will be displayed in list items (li). Once the limit of 5 tools is reached, a message 'Thanks for your suggestions' should appea ...

"Handling API Calls with AngularJS: Dealing with the [object object] Response

Looking for some guidance on pulling a list of articles from the NPR API. I have a functioning URL that returns JSON data. However, in my controller code, I seem to be having trouble accessing the object. When I use console.log to check, it just shows [obj ...

Please provide pattern block links and any special characters as input

I have a promotion box where users can input text to send to administrators. Objectives I need to prevent users from inputting links and special characters. Users should only be able to input letters a-z (case insensitive) and numbers 0-9. Input is option ...

Is there a way to seamlessly update the content across all devices being used in a Rails app?

I'm completely stumped on how to tackle this issue. I want the app users to instantly see any new posts added or removed by the admin without having to manually refresh the page. After some research, I came across websockets as a potential solution. H ...

What to do when encountering a 404 Error with `meta.json` in a Next.js Application

Hello fellow developers, I'm currently facing a challenge with my Next.js application. Upon running it, the terminal keeps throwing a meta.json 404 error, and I'm stuck on how to resolve it. Here are some key points for context: The Next.js app ...

Release a stationary element upon scrolling down the page

I have a calculator feature on my website which was coded in php. At the end of this calculator, there is a section that displays the results. While the results div works properly on desktop, I am looking to implement a fix for mobile devices. Specificall ...

Substitute a single occurrence of the dollar sign with an HTML tag

I have been attempting to insert an HTML tag into a price on my e-commerce website. Specifically, I am looking to add a tag between the "$" and the numerical value (e.g. $5.00), but I am unable to locate the core file where I can place the code between the ...

What is the best way to create a dynamic icon using React and TypeScript?

Excuse me, I am new to using React and TypeScript. I'm having trouble getting the icon to change based on the status in AppointmentType. The body color is working fine, but the icons are not changing. Can someone please help me solve this issue? const ...

Typescript version 2 is facing difficulties in resolving an external node module

Lately, I've been experimenting with prototyping using koa and Typescript 2.0. In my simple project, I've configured the tsconfig.json file like this: { "compilerOptions": { "outDir": "./bin/", "sourceMap": true, "no ...

How can we determine the total number of mandatory fields in an AngularJS form?

Can you explain how to calculate the number of required fields in a form using AngularJS? In my form, there are two required fields (email and select view). I want to display the count on my page - showing 2 if email is filled, 1 if only email is filled, a ...

Is it possible to use the jQuery .ajax() method to parse a javascript object that contains XML data?

Currently, I am facing a challenge parsing a javascript object that contains xml data within the .ajax() call using jquery. Can anyone provide guidance on how to accomplish this task? Any help would be greatly appreciated. Thank you! ...

Maintaining state value during client-side navigation in NextJs with Next-Redux-Wrapper

Currently, I am working on resolving the hydration issue that occurs when using wrapper.getServerSideProps. The problem arises when I reroute with the existing setup and the store gets cleared out before adding new data. This leads to a blank page as essen ...

Firestore is failing to accept incoming data when the setDoc method is employed

I am encountering an issue with my app's connectivity to the Firestore database when attempting to utilize setDoc. The database is successfully operational for next-auth, creating records as intended. However, the problem arises when trying to enable ...

Incorrect outcome when utilizing ajax to update a div within a for each loop

For a while now, I've been facing an issue with a div and form within a forEach loop. When one of the forms in the loop is submitted, the content inside the corresponding div is updated in the database and refreshed using JavaScript and Ajax. The upda ...