The getJSON API functions properly on a local machine but encounters issues when deployed on a

I have a vision to create a web application that can display the weather of any city based on user input. I've divided my project into three files - index.html for collecting user input, index2.html for retrieving and displaying the data, and a CSS file for styling. Everything works perfectly when I run the website locally using Chrome. However, once I upload the files to a web server, the $.getJSON function stops working. It used to work fine initially but after making some changes, it stopped functioning properly. Even simplifying the code doesn't help as it still fails to execute. Interestingly, the same code runs flawlessly when executed locally. Upon debugging, I found out that everything gets executed except for the getJSON API call.

Here's the content of the index file:

<!DOCTYPE html>
    <html>
    <head>
    <title>Welcome</title>
    <link rel="stylesheet" type="text/css" href="style.css"></link>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>

    <body id="page1">
    <center>
    <img src="sun.png" alt="Loading Screen" id="Icon" style="width:100px;height:100px;">

    <h1>WeatherPro</h1>

    <form action="index2.html" method="GET">
    <input type="text" id="input" name="keyword" placeholder="City">
    <br>
    <button type="submit" id="submit">Get Weather</button>
     </form>

     </center>
     </body>
     </html>

And here's the second file:

<!DOCTYPE html>
    <html>
    <head>
    <title>Weatherinfo</title>
    <link rel="stylesheet" type="text/css" href="style.css"> </link>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script defer src="https://use.fontawesome.com/releases/v5.0.7/js/all.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>

    // JavaScript functions go here

   </script>

       </head>
       <body id="page2">

      <!-- HTML content goes here -->

   </body>
   </html>

Finally, the CSS styling:

/* CSS styles go here */

Answer №1

The variable urlParams is not defined.

I have not utilized new URLSearchParams(queryString);, so I am uncertain about its functionality, but it does not seem to be functioning correctly in my beta version of Chrome.

You can achieve the same result without using urlSearchParams.

function getWeather(){
    const params = window.location.search.replace('?','&').split('&');
    const keyword = params.filter(v => v.indexOf('keyword') > -1)[0].split('=')[1];
    if(keyword){
        var link= "https://api.openweathermap.org/data/2.5/weather?q="+keyword+"&APPID=myAPI";
        $.getJSON(link,function(json){
          var temperature = json.main.temp;
              temperature = temperature - 273.15;
          var roundTemp = Math.round(temperature*10)/10;
          document.getElementById("TempID").innerHTML = roundTemp;
        });
    }else{
        // keyword not found
    }
}
getWeather();

For a functional example, here is the live repl.it link ()


If you need to retrieve another value, simply modify the line related to the desired value like this:

const units = params.filter(v => v.indexOf('units') > -1)[0].split('=')[1];

If you plan on querying multiple values, consider creating a separate function for this.

function urlQuery(str){
    const params = window.location.search.replace('?','&').split('&');
    return params.filter(v => v.indexOf(str) > -1)[0].split('=')[1];
}
var keyword = urlQuery('keyword');

Answer №2

A breakthrough! After some investigation, it turned out that changing the var link of the web service to https instead of http was the key to solving the issue.

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

Ways to resolve the issue of truncated lines while displaying HTML content in WebView on Android devices

When displaying content in a WebView, I am encountering an issue where the top and bottom lines are being cut off. What steps can I take to resolve this problem? My current approach involves using HTML to present data within the WebView. ...

What is the process for verifying JSON format validation?

When my program receives a JSON file containing information for a service, I need to verify its validity (checking if all necessary keys exist) before running the service program. The standard JSON format required for this program is as follows: { "se ...

Formatting numbers in Angular 2 to include a space every three zeros in a money amount

Let's say I have the number 30000 and I want to format it as 30 000. What method should I use to achieve this? Here are more examples: 300000 -> 300 000, 3000000 -> 3 000 000. Just to clarify, this is not about using dots or commas, but rather reco ...

Ways to incorporate NPM packages into your browser projects using TypeScript

This is the current setup: index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <script src="../node_modules/systemjs/dist/system.js"></script> <script src="../node_modules/lodash/in ...

What are some alternative ways to link a local MongoDB database to my Android Studio application instead of using MongoLab?

Can someone please help me figure out how to connect my Android Studio project to a MongoDB database stored locally on my PC? I've been searching for solutions that don't involve using MLab, but I haven't had any luck. I've attempted f ...

Improving the efficiency of JSON data retrieval in JavaScript

I possess a hefty 10MB JSON file with a structured layout comprising 10k entries: { entry_1: { description: "...", offset: "...", value: "...", fields: { field_1: { offset: "...", description: "...", ...

Storage in Ionic and variable management

Hello, I'm struggling to assign the returned value from a promise to an external variable. Despite several attempts, I have not been successful. export class TestPage { test:any; constructor(private storage: Storage) { storage.get('t ...

The integration of signalR with jquery mobile is posing several challenges

Recently, I started working with jquery mobile and signalR to implement a calling feature in my mobile app. However, I encountered an error that looks like this: http://localhost:2286/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%2 ...

Steps for rearranging the order of CSS grid layout

Could you assist me in implementing a grid layout that fulfills these specific criteria? I'm unsure of how to proceed, so any guidance would be greatly appreciated. When there are more than 9 items, the current layout changes the order from top to bo ...

Tips for removing "<li>" elements using JavaScript

My issue remains unresolved... I created a tree structure in MVC and added JavaScript code for expanding and collapsing the tree. However, after applying the code, my tree is not being displayed correctly. enter image description here In the image, you c ...

Designing a sequential bar graph to visualize intricate data using AmCharts

I received the following response from the server in JSON format: [{ "data1": { "name": "Test1", "count": 0, "amount": 0, "amtData": [ 0,0,0,0 ], "cntData": [ 0,0,0,0 ], "color": "#FF0F00" }, "data2": { ...

Website layout looking unique due to pixel width adaptation from standard width

I'm currently working on a website with full width design. On my computer, the website displays as full width, but on other computers it shows extra space on the sides. How can I ensure that this website is truly full width? .wrapper_boxed { wid ...

How can I change the transparency of a CSS background color using JavaScript?

I have a question about CSS: .class1 { background: #fff } Now, I need to achieve the following: .class2 { background: rgba(255,0,0,0.5) }; Is there a way to use JavaScript only to change the background property of .class1 and give it an opacity of 0.5? ...

Using Vue Js directive to implement a Select2 component

I've been exploring the example of the Vue.js wrapper component and trying to customize it to use a v-select2 directive on a standard select box, rather than creating templates or components for each one. You can view my implementation in this JS Bin ...

What is the best way to enclose a bootstrap row within a clickable link generated by the twitch.tv API?

Recently, I completed a JSON/JavaScript project for Free Code Camp that retrieves streamer information like their logo, current status, and display name. My goal is to enclose entire Bootstrap 3 rows in hyperlinks linked to the streamers' pages, elim ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

Encountering an issue when attempting to downgrade React Native version from 0.51 to 0.45

My current project requires me to downgrade due to certain third-party packages not being updated for the latest version of react-native. Specifically, I am using Xcode 9.0. Despite my efforts to downgrade the react-native version, I encountered the follo ...

Angular 2 TypeScript: Accelerating the Increment Number Speed

I'm working with a function in Angular 4 that is triggered when the arrow down key is pressed. Each time the arrow down key is hit, the counter increments by 1. In this function, I need to run another function if the counter reaches a certain speed. ...

What is the best way to extract the innerHTML of every button and exhibit it in a text box?

How can I create a simpler JavaScript code for clicking buttons to input letters into a text box? Instead of creating getElementByID for each button, is it possible to use some kind of loop? <div id="alpha" > <br/> <div align="cente ...

Creating a JSON array from the values in a single column in SQL involves combining all the values into a structured JSON

Need assistance with transforming the result of a SQL query into a JSON array. Here's the SQL query: SELECT CP.PageID FROM CommClient.dbo.ClientPage AS CP INNER JOIN CommApp.dbo.Page as P ON CP.PageID = P.PageID INNER JOIN CommApp.dbo.PageGroup as P ...