The weather app on my webpage is not showing any data

A weather application is currently in progress, but I am encountering issues with the display of temperature, country, and current weather description. It seems that the problem emerges after the HTML geolocation function. I suspect that the function is having difficulty parsing through the data provided by the weather API.

Below is my code:

$( document ).ready(function(){

  if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
  } else {
      x.innerHTML = "Geolocation is not supported by this browser.";
  }


  function showPosition(position) {
var lat = "lat= " + position.coords.latitude; 
var lon = "lon= " + position.coords.longitude;
getWeather(lat,lon);
  }

   function getWeather(lat,lon){
var urlstring = "https://fcc-weather-api.glitch.me/api/current?" + lat + "&" + lon;
$.ajax({
    url : urlstring,
    dataType : "jsonP",
    success : function(data){
        var temp = data.main.temp;
        var desc = data.weather[0].description;
        var country = data.sys.country;
        $("#desc").html(desc);
        $("#temp").html(temp);
    }
})
  }

  var ctof = $("#c/f").click(function(){
     var cel = Math.round((temp - 32) * 5 / 9);   
     var faren = Math.round((temp * 9 / 5) + 32);
     if(ctof == true){
        $("#temp").html(faren);
      }
      else{
        $("#temp").html(cel);
      }
        }) 
  });

The following is the accompanying HTML code for reference purposes:

<!DOCTYPE html>
<html>
<head><title>Web App</title></head>
<body>
<div class="container">
   <div class="row">
     <header class="col-xs-12 text-center">
       <h1>Free Code Camp </h1>
       <h1>Weather App</h1>
     </header>

     <div class="col-xs-8 col-xs-offset-2">
       <div class="text-center status">
         <p><span id="city"></span> <span id="country"></span></p>
         <p><span id="temp"><button id="#c/f">C/F</button></span></p>
         <p id="desc"></p>
       </div>
   <div class ="info">
 <div class="develop">Developed by = Shumaila Bi Shaikh</div>
 <div class="langs">Created by: HTML,CSS,ANGULARJS</div>
 </div>

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

Answer №1

Have you attempted logging the variable desc or other data values? It appears that you may be retrieving the necessary arrays, but trying to directly insert them into your html, which may not produce the desired outcome...

Instances such as these:

    $("#desc").html(desc);
    $("#temp").html(temp);

This approach will not yield results unless you are providing valid HTML strings like <p>Hello</p>. In this scenario, you are working with arrays. You must first determine how you want your data to appear visually, and then utilize your .html() functions accordingly.

Considering your data structure, a solution could involve:

let descString = "";
desc.forEach(value => descString += "<p>" + value.something + "</p>")
$("#desc").html(descString)

Answer №2

The issue lies within this particular line of code:

var ctof = $("#c/f").click(function() {

If you need to select an element with characters that are used in CSS notation, you must escape them by adding a \\ before them. For more detailed information, refer to the documentation.

To correct this issue, modify the line to be:

var ctof = $("\\#c\\/f").click(function(){

Another problem can be found in this line of code:

<p><span id="temp"><button id="#c/f">C/F</button></span></p>

When obtaining the data.main.temp, it ends up overwriting and removing the button. To fix this, update the line as follows:

<p><span id="temp"></span><button id="#c/f">C/F</button></p>

In order to enable geolocation in Chrome browser, you will need to follow the steps outlined in this helpful answer

For a demonstration, you can visit the provided fiddle

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

Is there a way to send an AJAX request to an MVC action from a JavaScript file?

In a file named job.js, there is code that works perfectly when run on localhost but results in a 404 error when run on an intranet server with an application name. Job.updateJob = function () { $.post('/Builder/ListJobItems', function (dat ...

Scraping a URL that functions perfectly on Firefox without the need for cookies or javascript results in a

Despite blocking all cookies and turning off JavaScript on Firefox, I encounter an issue when attempting to scrape a URL using Python's urllib module. The error message HTTP Error 403: Forbidden is returned. I have ensured that I am using the same use ...

Unable to retrieve data on the frontend using Node.js and React

I have been attempting to retrieve all user data from the backend to display on the webpage. However, it seems that the getAllUsers() function is not returning a response, as no console logs are being displayed. Here is my ViewUsers.js file: import React, ...

Provide the email address to use on the forum

Is there a way to code an email address in HTML that will be invisible and undetectable by forums? Thank you in advance. I'm looking for a more advanced solution like this one! <h>mariaburkke76</h><h><h><h><h>< ...

JavaScript nested function scope loss issue is being faced

Could someone provide an explanation of the scope binding in this code snippet? window.name = "window"; object = { name: "object", method: function() { nestedMethod: function() { console.log(this.name); ...

Utilize a Web Api controller to authenticate and verify the data input in

Currently, I am working on a web API application that includes the following form: <form id="editForm"> <input id="editid" type="hidden" name="id" /> <p><label>Numéro cnss </label&g ...

The second tab on Bootstrap5's tab content feature seems to generate an endless amount of white

I am working on a project where I need to display statistics for both the current month and year. To organize this data, I created a card with tabs for each - one tab for the month and another for the year. By default, the month tab is loaded first. Howev ...

Headers can't be set after they have been sent. This issue arises when calling create(data,cb) function

I am a beginner in Node.js and I am attempting to create a model in MongoDB. However, when I make a call to localhost:3000/a, I notice that the request is being sent twice in the console and I am encountering an error stating "Can't set headers after ...

Is the $http call for OPTIONS instead of POST?

Hey there, I'm encountering a strange issue while trying to call my backend using the POST method. Remote Address:192.168.58.183:80 Request URL:http://192.168.58.183/ESService/ESService.svc/CreateNewAccount Request Method:OPTIONS Status Code:405 Meth ...

Having trouble with jQuery AJAX - page continually refreshes upon submitting and data isn't being transmitted

I've been working on creating a dynamic AJAX function using PHP and MySQL to update database records without the need for page refresh or navigation. However, I haven't had much success with it yet. Here's the code I have on the page with t ...

The Spring MVC controller is not designed to handle direct AJAX requests

In my server-side controller, I have the following method: @RequestMapping(value = {"/templates/test"}, method = RequestMethod.POST, consumes = "application/json") @ResponseBody public String TestURL(@RequestBody List<String> testString, ...

Having difficulty understanding the JSON response from the REST API

I received a JSON REST API response from a URL. I am struggling to parse the JSON data. Despite trying various solutions, I am unable to retrieve the data. The response is messy, but it contains the necessary information. All the JSON objects are w ...

Preserve final variable state - Angular

My function looks like this: flag: boolean = false; some_function(){ var foo = some_num_value; var bar = foo; // Storing value in a separate variable if(this.flag){ v ...

Changing characters to asterisks using Javascript

I am currently working on a function that transforms all characters after the first word into asterisks. For example, if I have MYFIRSTWORD MYSECONDWORD, I would like it to show as: MYFIRSTWORD *** Currently, I'm using the code below which replaces ...

Showing a PHP-generated table with drill-down rows using jQuery Datatables

I have been working on implementing drill-down functionality in a datatable using a PHP file as the data source. However, I am encountering some difficulties that I can't seem to resolve. I have been referring to the guide provided at http://datatable ...

React Query: obtaining the status of a query

In the realm of React Query, lies a valuable hook known as useIsFetching. This hook serves the purpose of indicating whether a particular query is presently fetching data. An example of its usage can be seen below: const queryCount = useIsFetching(['m ...

What is the best way to extract a value from a JSON object?

I am having trouble deleting data from both the table and database using multiple select. When I try to delete, it only removes the first row that is selected. To get the necessary ID for the WHERE condition in my SQL query, I used Firebug and found this P ...

Executing a Node.js program using the command line without having to type out the word 'node'

I am currently working on a Node.js package that includes a command-line utility. Right now, alacon.js is situated in the root of the package. To execute this utility, I have to use the word node followed by the utility's name, like so: node alacon ...

Is it possible to seamlessly alternate between JSON using the Jackson processor and XML using XStream, or is it feasible to use both formats simultaneously

I am in the process of developing a Web Server that can convert an Object into both JSON and XML formats. I have successfully used Jackson to serialize an object into JSON through my REST Interface, but I also need to support XML serialization. Recently, ...

The $scope.$watch function is not triggering events within a controller of a ui.bootstrap.modal

Currently, I am utilizing UI bootstrap for Angular and have successfully integrated the ui.bootstrap.modal component into my project. Everything seems to be working smoothly except for one issue I am encountering. Despite setting up a $scope.$watch to trac ...