The JSON request object has not been defined

I am currently facing an issue while trying to make a JSON request from the open weather API example. When I attempt to access the key value in the $.each method, it keeps showing that the value for the key is undefined. Can someone please review the code and help me identify what I am missing?

function getGs(data) {
  $.each(data.main,function(i,weather){
    console.log(weather.humidity);
  })
}

$(document).ready(function() {
  var bggAPI = "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139?";
  
  $.ajax({
    dataType: "json",
    url: bggAPI
  });
  
  getGs();
  
});

Answer №1

$.ajax initiates an asynchronous request.
After it successfully completes, the success function is triggered and you may have missed it.

data.main is not a list, but rather an object.
data.weather is a list.

function getGs(data) {
  console.log(data.main.humidity);
  $.each(data.weather,function(i, weather) {
    console.log(weather.main);
  })
}

$(document).ready(function() {
  var bggAPI = "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139?";

  $.ajax({
    dataType: "json",
    url: bggAPI,
    success:getGs
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

It seems like a simple issue, you have a typo in your code.

You have used wather as a parameter but are calling weather inside your function.

Update:

Upon reviewing your provided JSON data :

{ coord: { lon: 138.93, lat: 34.97 }, weather: [ { id: 800, main: "Clear", description: "Sky is Clear", icon: "01n" } ], base: "cmc stations", main: { temp: 300.37, pressure: 1015, humidity: 82, temp_min: 300.37, temp_max: 300.37 }, wind: { speed: 0.51, deg: 314, gust: 1.03 }, clouds: { all: 0 }, dt: 1438897427, sys: { type: 3, id: 10294, message: 0.0102, country: "JP", sunrise: 1438804655, sunset: 1438854132 }, id: 1851632, name: "Shuzenji", cod: 200 }

You have a weather array, however, you are iterating through the main property as an array when it is actually just a property within the weather array. Your corrected code should be:

$.each(data.weather,function(i,weather){
  console.log(weather.main);
  })
}

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

After Vue 3 <router-view> was built in history mode, it received comments

My Vue project works perfectly in hash router mode, but when I switch to history mode, only the navbar is displayed and the <router-view> is commented out. I have already configured my apache settings for history mode. router.js import { createRoute ...

Creating an X pattern on an HTML5 canvas and detecting intersections with a perimeter

I am currently developing a maze game using HTML 5. Below is the function I have implemented to draw an "X" on the canvas (the player will guide the X through the maze using touchpad). dim = 8; function rect(x,y,xdim){ ctx.beginPath(); ctx.moveT ...

Using a basic string as the JSON response in a Spring REST controller

Consider this simple test controller implemented with Spring 4.0.3: @RestController public class TestController { @RequestMapping("/getList") public List<String> getList() { final List<String> list = new ArrayList<>() ...

Is the Facebook AJAX Permissions Dialog displayed outside of a Pop-Up?

I have conducted extensive research but have failed to find a clear answer to my query. Although there is plentiful information on Facebook API AJAX/PHP communication, I am unable to locate an example where the Permission Dialog for an app (showPermissionD ...

utilize the getStaticProps function within the specified component

I recently started a project using Next.js and TypeScript. I have a main component that is called in the index.js page, where I use the getStaticProps function. However, when I log the prop object returned by getStaticProps in my main component, it shows a ...

JavaScript can be used to target and remove parent <tr> elements that contain empty <td> elements with a specific class

I am facing a challenge with a large HTML table that is populated by variables set in JavaScript from my database response. When the database returns an empty string, I want to remove the entire parent row using JavaScript. Although I have attempted to us ...

Having difficulties transmitting numerical values through res.send() in express with node

Currently, I'm faced with a challenge in my express application on node.js as I attempt to retrieve the "imdb rating." movies.json [{ "id": "3962210", "order": [4.361276149749756, 1988], "fields": { "year": 2015, "title": "David and Goliath" ...

What is the counterpart of the JavaScript transport.responseText in jQuery's Ajax requests?

I'm currently in the process of converting my JavaScript Ajax request to jQuery's ajax. Here is an example of my existing JavaScript Ajax code: new Ajax.Request(url, { method: 'post', onSuccess: function(transport) { ...

Selenium WebriverJS does not support right mouse button clicks in PhantomJS

Currently, I am utilizing Selenium in combination with WebdriverJS to automate a straightforward web application. However, an issue arises when transitioning from Chrome to PhantomJS, resulting in the test not functioning as intended. Specifically, the rig ...

What is the best way to verify the accuracy of a value in JavaScript as I move forward?

My JavaScript code prompts the user to input an entry, displays a list of entries, and allows for deletion. However, there is an issue when the user enters "delete" followed by an invalid number. The code asks for a correct index, but if the user continu ...

Assigning numerous key-value pairs as the value of a single key in AngularJS

I need assistance with creating an array that contains objects with key-value pairs from another array of objects. Specifically, I am looking to assign a group of objects in an array (from a Request JSON) as the value for a key within another array. Can so ...

Can you provide guidance on creating a JSON-LD Schema for a GeoShape Circle?

Seeking advice on how to create the schema for a GeoShape Circle. I need to establish a coverage area for my service-based business, despite not having a physical location. My goal is to cover a 30-mile radius in all directions from Sacramento, CA. Here ...

The browser does not store the cookie in the designated cookie tab within the application settings

Upon sending a login request, although the cookie is being received, it is not getting saved in the cookie tab under the application tab. Consequently, when other protected routes' APIs are accessed, the cookie is not available to req.cookie on the ba ...

Error encountered: Index 109 - The function $.ajax(...).success is not recognized as a valid function while working with jQuery in a Node

I'm just starting to learn about jquery and have been experimenting with ajax in my recent code. Below is the snippet of what I have implemented: $(function(){ $("#status").change(function(){ if($(this).is(':checked')) ...

JavaScript Oddity - Array Increment Trick

What is the reason behind ++[[]][0] == 1 While trying to do ++[] leads to an error? Shouldn't they produce the same result? My understanding is that the first example performs an index-read on the array, resulting in an array within an array. The ...

How to extract parameters from an http get request in Node.js

Trying to handle an HTTP request in this format: GET http://1.2.3.4/status?userID=1234 I am unable to extract the parameter userID from it. Despite using Express, I am facing difficulties. Even when attempting something like the following, it does not yi ...

What is the best way to have a variable adjust each time a coin is inserted until it reaches a specific value?

I have developed a unique coin box that recognizes the value of each coin inserted. Users can now pay for a service that costs 2.0 € by inserting coins of various denominations such as 2.0 €, 1.0 €, 0.50 €, 0.20 €, and 0.10 €. In my react-nati ...

Tips for displaying an uploaded image using the Valums file uploader

I recently implemented the Andrew Valums File Uploader on my website and it's functioning as expected. I am now looking to modify it so that instead of displaying just the uploaded filename and size, it will show the uploaded picture directly in the b ...

A guide on assigning a value to an array within a formgroup

if (Object.prototype.hasOwnProperty.call(data, 'checklists')) { if (Array.isArray(data.checklists)) { data.checklists.map((dt: any) => { dt.tasks.forEach((task: any) => { const dataArray = new FormGroup({ ...

Encountering errors while running Angular 8's ng build prod command

After successfully migrating my project from Angular 7 to Angular 8, I encountered an issue when attempting to run 'ng build prod' which resulted in the following error: ERROR in Error during template compile of 'Ng2CompleterModule' Cou ...