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 (https://repl.it/repls/SaneRustyMemwatch)


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

Utilizing Promise.all to update subdocuments with Mongoose

Encountered an error while checking the value in promiseArr, seeking assistance or suggestions for a better approach. Thanks! **Error** <rejected> { MongooseError: Callback must be a function, got [object Object] at new MongooseError (D:\P ...

Enhance a query parameter in a Node.js application

When using Node.js / Express, I define a path and pass in a request and response. My goal is to always include a seed URL parameter when this path is accessed. Initially, I set the seed query param to 0 and redirect the URL. Next, I want to randomize tha ...

Is it possible to animate CSS Grid components?

Is it possible to animate a re-ordered set of elements in an array that are arranged using a CSS Grid layout? Check out this quick boilerplate ...

The value buried within multiple layers of JSON tags

I am dealing with a complex JSON string that is deeply nested. Here is an example of the structure: { "decisionElements": [ { "serviceName": "PreciseId", "applicantId": "APPLICANT_CONTACT_ID_1", "decision": ...

What is the reason behind re-rendering pages specifically for error messages in express and nodejs?

In the world of web development, it is commonly accepted practice to re-render a page to display error messages and redirect to show success messages. While implementing this principle in my code using express js, I have encountered a few challenges. For ...

The ability to choose only one option in a checkbox within a grid view column

In my grid view, I have a checkbox in the last column. I am trying to ensure that only one row can be selected at a time. <tr *ngFor="let permit of PermitDetails" (click)="GoByClick(permit)"> <td style="text-align: center">{{permit.TVA_BAT ...

What could be causing this slider to malfunction in Firefox?

I have recently developed a slider on this page: While the slider functions smoothly in Chrome, I am facing compatibility issues with Firefox. Can anyone shed some light on why this might be happening? Here is the HTML, CSS, and JS code used for the slid ...

Error in sending data to the server via the specified URL: "Http failure response for http://localhost/post.php: 0 Unknown Error" and POST request to http://localhost/post.php failed with error code

Feeling a bit stuck trying to add data to my database. As a junior with PHP and Angular, I am using PHP via XAMPP and Angular 8. Is it possible to create separate files for the post and get methods in the PHP file? app.component.ts import { Component, O ...

What is the best way to display my 'React Loading Spinner' component at the center of my view?

Whenever I use the Loading as my parent component for the Layout component, it always shows up in the center of the page instead of within my view. How can I adjust its positioning? ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

What steps should be taken to configure Multer so that it delays saving an image until after a successful database entry using Mongoose has been made?

In the typical Multer setup, files are saved immediately, as illustrated in the following basic example: const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); const app = express(); app.post('/profile&apo ...

Setting cookies in Express will not work if you are using res.sendFile()

After implementing the res.sendFile() function, I noticed that the set-cookie header is not being received in the response. app.get(sessionTracker, (req, res, next) => { res.cookie('tracker', '123a', { maxAge: 172800000, h ...

Move the dropdown selection above all DIV elements

Check out this link: Make sure to select an option from the dropdown menu. Also, some of the options are hidden behind other elements. I noticed that if I target .join-form and remove overflow: hidden, the layout of the page becomes distorted. Can anyon ...

Struggling to get custom CSS to apply properly in Joomla 4 with Bootstrap 5 template

Having created a simple Bootstrap 5 template for my Joomla 4 website, I've been attempting to customize the navbar with CSS in my user.css file. However, it seems that the styles added in user.css are not being applied. I have verified that user.css ...

Issues with Collision Detection between Canvas Rectangles and Balls

I am developing an HTML5 canvas game and encountering an issue with collision detection. The problem occurs when the ball collides with any platform - the ball's gravity should change to -1 and move upwards at the same velocity as the platforms. Howev ...

Using PM2 to Manage Your PHP Scripts in Cluster Mode

Currently, I have been effectively managing single instances of PHP daemons with PM2, and so far everything is running smoothly! When it comes to managing Node.js/IO.js apps with PM2, I can easily launch them in cluster mode without any issues. However, t ...

Utilizing jQuery for animating SVG elements with dynamic color changes and scaling effects upon hover

Seeking assistance from coding experts! I have created an icon and am attempting to modify it so that the color changes when hovered over. Additionally, I want the white square to scale down by 50% starting from the top-left corner of its current position. ...

vue-form and vue-material are not compatible with each other

In my experience, using a Vue form on a regular HTML <input> element allows validation to work as expected. However, when I switch to using the <md-input> element, the validation no longer functions and an error message is displayed: Element ...

Issues with jQuery animate.css functionality specifically occurring on Firefox browser

As a beginner in jQuery, I have been exploring different animations and recently came across an issue with Firefox compatibility. I discovered the animate.css library, and decided to incorporate its animations into text captions on a slider using the Soli ...

Executing functions and setting element values upon loading in Javascript

I am currently working on updating a small Javascript function that assigns an active class to the parent <div> of a group of radio buttons when the page loads and also when there's a change event. The existing function looks like this: functi ...