JSONP OpenWeather API

I've been trying to access and retrieve weather data from OpenWeather using their API, but unfortunately, I'm facing some difficulties in getting it to work. It seems like there might be an issue with the way I am fetching the JSON data.

To query their data, I've used the following code snippet (you can find it on JSFiddle here):

function getWeather(lat, lon, callback) {
    var weather = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&cnt=1';
    $.ajax({
        dataType: "jsonp",
        url: weather,
        success: callback
    });
};

The query I made returned the following JSON response:

{
 "coord":
   {
    "lon":-6.27,"lat":13.34
   },
 "sys": 
   {
    "message":0.0088,
    "country":"ML",
    "sunrise":1390719134,
    "sunset":1390760592
   },
 "weather":
 [
   {
    "id":800,"main":"Clear",
    "description":"Sky is Clear",
    "icon":"01n"
   }
 ],
 "base":"cmc stations",
 "main": 
   {"temp":293.154,
    "temp_min":293.154,
    "temp_max":293.154,
    "pressure":989.21,
    "sea_level":1024.43,
    "grnd_level":989.21,
    "humidity":64
   },
 "wind":
   {
    "speed":4.1,
    "deg":52.0018
   },
 "clouds":
   {
    "all":0
   },
 "dt":1390695239,
 "id":2451478,
 "name":"Segou",
 "cod":200
}

Next, I attempted to format the response like this:

var lat = 13.3428;
var lon = -6.26612;

getWeather(lat, lon, function (data) {
    var tempHTML = "";
    tempHTML = tempHTML + '<h3>WEATHER INFO:</h3>';
    tempHTML = tempHTML + 'Weather data received <br/>';

    tempHTML = tempHTML + '<h3>WEATHER:</h3>';
    tempHTML = tempHTML + 'Weather Id: ' + data.weather[0].id + '<br/>';
    tempHTML = tempHTML + 'Weather Main: ' + data.weather[0].main + '<br/>';
    tempHTML = tempHTML + 'Weather Description: ' + data.weather[0].description + '<br/>';
    tempHTML = tempHTML + 'Weather Icon: ' + data.weather[0].icon + '<br/>';

    tempHTML = tempHTML + '<h3>MAIN:</h3>';
    tempHTML = tempHTML + 'Temperature: ' + data.main[0].temp + 'degrees<br/>';
    tempHTML = tempHTML + 'Temperature Min: ' + data.main[0].temp_min + 'degrees<br/>';
    tempHTML = tempHTML + 'Temperature Max: ' + data.main[0].temp_max + 'degrees<br/>';
    tempHTML = tempHTML + 'Pressure: ' + data.main[0].pressure + 'Kpa<br/>';
    tempHTML = tempHTML + 'Humidity: ' + data.main[0].humidity + '%<br/>';

    tempHTML = tempHTML + '<h3>WIND:</h3>';
    tempHTML = tempHTML + 'Wind Speed: ' + data.wind[0].speed + 'kmh<br/>';
    tempHTML = tempHTML + 'Wind Direction: ' + data.wind[0].deg + 'degrees <br/>';

    tempHTML = tempHTML + '<h3>CLOUDS:</h3>';
    tempHTML = tempHTML + 'Cloud Coverage: ' + data.clouds[0].all + '%<br/>';

    document.getElementById('weather_output').innerHTML = tempHTML;
});

However, when running my code in the JSFiddle, I encountered a console error:

Uncaught SyntaxError: Unexpected token : api.openweathermap.org/data/2.5/weather?lat=13.3428&lon=-6.26612&cnt=1&callback=jQuery191009959305939264596_1390699334749&_=1390699334750:1
Uncaught TypeError: Cannot read property 'temp' of undefined (index):36

Answer №1

Upon examining the JSON response, it is clear that the main key references an object rather than an array. Therefore, trying to access it with [0] will result in an error.

To resolve this issue, you should utilize data.main.temp instead for retrieving the temperature information.

This same principle applies to the wind, sys, and cloud properties within the JSON data.

Lastly, don't forget to include the final letter L in the innerHTML method towards the end of your code.

For a demonstration showcasing all these corrections, you can visit: http://jsfiddle.net/KLtLD/17/

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

Returning draggable elements to their original placement

I'm looking to create a custom function that resets my draggable elements to their original positions when invoked. This is not related to the built-in revert functionality. $('.drag').draggable({ stack: ".drag", snap: ".dro ...

Activate/Deactivate toggle using Vue.js

new Vue({ el: '#app', data: { terms: false, fullname: false, mobile: false, area: false, city: false, }, computed: { isDisabled: function(){ return !this.terms && !this.fullname && !this.mob ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...

Incorporating a File Attachment within a JSON Structure

Can a file attachment be included in a JSON Object? I am working on an HTML Form with text field inputs and a file attachment, and I would like to send all this form data (including the file attachment) as a JSON Object to the server. Are there any specif ...

Generate a flexible JSON array in VB.NET

Looking to generate a flexible array that can be converted into a JSON array for visualization with Morris charts. The usual approach in VB.NET is as follows: Dim xArray(2) xArray(0) = New With {Key .TradingDay = "Day1", .Seller1 = 1500, .Seller2 = 160 ...

Utilizing ProtractorJS to Extract Numbers from Text within an Element and Dynamically Adding it to an Xpath Expression

Situation My objective is to extract text from an element on a webpage, convert that extracted text into a number in string format, and then use it for an xpath query. The code snippet below illustrates this process: var bookingRefString = element(by.css ...

At what point should the term "function" be included in a ReactJS component?

As a beginner in ReactJS, I have been working through some tutorials and noticed that some code examples use the keyword function while others do not. This got me wondering what the difference is and when I should use each one. Render Example with functi ...

Using Observables in Angular 2 to send polling requests

I have the following AngularJS 2 code snippet for polling using GET requests: makeHtpGetRequest(){ let url ="http://bento/supervisor/info"; return Observable.interval(2000) .map(res => res.json()) //Error here ...

Error: Unable to cast value "undefined" to an ObjectId for the "_id" field in the "User" model

Whenever a user logs into their account, I am trying to retrieve their data on the login screen. The login functionality itself works perfectly, but unfortunately, the user data is not displaying. I have tried troubleshooting this issue by making changes i ...

The "smiley" character added to the information during an Ajax call

Encountering an unusual issue. A colon (:) character is being appended to the JSON data sent to the server via AJAX request. https://example.com/image1.png The colon character seems to appear after sending the JSON, but it does not show up when inspectin ...

Obtaining zip files using AngularJS

Upon entering the following URL in my browser, I am prompted to download a file: My goal is to download this file using an AngularJS HTTP request. I have created a factory for this purpose, but unfortunately, the download is not successful. Even though ...

Issue with the positioning of the datepicker is not functioning properly

I'm currently facing an issue with the position of a date picker plugin from jquery. The search box on my website allows users to select a range of dates using the date picker, but when enabled, the date picker appears at the bottom left corner of the ...

Add the word "String" in front of the moment timestamp

In my project, I have used React along with Material UI to show the message Running check... when the clicked state is set to true. If it's not true, then I am displaying a timestamp by utilizing the react-moment library. <Typography gutterBottom ...

Tips on obtaining the ultimate URL using jQuery/AJAX

When executing $.get or .load with jQuery, the requests smoothly follow 302 redirects to provide me with the desired response. This response can be utilized in the callback function of $.get, or linked directly to the designated element for .load. Even th ...

Datatables ajax response not loading data into table

I don't have much experience with JavaScript, so I believe there may be a misconfiguration or something that I'm overlooking. My current setup involves using Datatables v1.10.7. I have a table with the required parts - a thead, tfoot, and a tbod ...

React encountered an unexpected termination of JSON input during parsing

Upon running npm install, I encountered an error that is shown in the following link: https://i.stack.imgur.com/nVvps.jpg This issue has been causing trouble for me today and I'm unsure of the reason behind it. ...

An Unexpected Token Leads to a SyntaxError in Jest's CSS-Modules

I have successfully configured my jest to allow the usage of static files by following their detailed documentation. However, despite implementing the instructions correctly, I am still encountering an error: What steps can I take to resolve this issue an ...

Initiate the process of displaying data on a datetime chart using Highcharts

I am currently developing a yearly chart, but I've encountered a small issue. The chart begins in January, however there is no data available until May. The client specifically wants the chart to only display when there is data available, and unfortu ...

Using Next.js: What is the process for dynamically registering the quill-blot-formatter to react-quill that has been imported on the client side rendering exclusively

Currently, I am dynamically importing the react-quill library on the client side only by setting ssr: false. My functional component is functioning properly, but I now want to integrate the quill-blot-formatter package into the modules section of my quill ...

Trouble arises when implementing AJAX in conjunction with PHP!

I am facing an issue with my PHP page which collects mp3 links from downloads.nl. The results are converted to XML and display correctly. However, the problem arises when trying to access this XML data using ajax. Both the files are on the same domain, b ...