A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to be fine. Can anyone help me identify what's wrong with my code so I can fix it? Also, if you could provide assistance using Javascript instead of JQuery, that would be great. Link:

This project is part of my Javascript learning journey. The apiKey is public.

<html>
<head>
        <meta charset="utf-8"/>
        <title>getting</title>
    <script>

        function start(){
            //console.log("asdasd");
            var requestURL = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true";
            var request = new XMLHttpRequest();
            console.log(request);
            request.open('GET', requestURL);
            //console.log(request.response);
        }
        window.addEventListener("load",start,false);
    </script>
</head>
<body>

    <div id="loading"></div>
</body>
</html>

Any assistance would be greatly appreciated.

Answer №1

Visit this link for more information on XMLHttpRequest response

Learn about async functions in JavaScript here

Explore the Fetch API in detail

Check out how to chain promises with then and catch

Remember to utilize JSON.parse on your data when needed

var requestURL = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true";


//ES5
function XMLrequest() {
  var request = new XMLHttpRequest();
  request.open('GET', requestURL, true);
  request.onreadystatechange = function() {
    if (request.readyState === 4) {
      console.log('XML', request.response);
    }
  }
  request.send();     
}

//ES6
function getWithFetch() {
  fetch(requestURL)
    .then(res => {
      console.log('fetch', res)
    })
    .catch(err => {
      console.log(err, 'fetch fail')
    })
}

// ES7
async function getWithAsycAwait() {
  try {
    const data = await fetch(requestURL);
    console.log('await', data)
  } catch(e) {
    console.log(e, 'await fail')
  }
}

getWithAsycAwait()
getWithFetch()
XMLrequest()

Answer №2

A couple of things to note: Firstly, it is important to actually send the request using the send() method. Secondly, if you are executing an asynchronous request, make sure to add a listener to handle the response:

request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200)
      console.log(request.response);
  };

  request.send(null);

If you prefer not to make the request asynchronous, you can pass false as the second parameter to your open() call. However, this approach is discouraged as it may result in blocking calls.

For more options and details on XMLHttpRequests, consider reading further on this resource from Mozilla

Check out this working example for reference

Answer №3

Here is a suggestion for you to try:

<html>
<head>
        <meta charset="utf-8"/>
        <title>fetching data</title>
        <script>
            function fetchData(){
                //console.log("asdasd");
                var requestURL = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true" ;
                var request = new XMLHttpRequest();
                console.log(request);
                request.open('GET', requestURL);
                request.send();
                //console.log(request.response);
            }
            window.addEventListener("load",fetchData,false);
        </script>
</head>
<body>

    <div id="loading"></div>
</body>
</html>

Alternatively, you could also consider this approach:

<html>
<head>
        <meta charset="utf-8"/>
        <title>fetching data</title>
        <script>
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                // Perform actions when the document is read;
                }
            };
            xhttp.open("GET", "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true", true);
            xhttp.send();
            window.addEventListener("load",fetchData,false);
        </script>
</head>
<body>

    <div id="loading"></div>
</body>
</html>

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

display a container and navigate to the specific link

Greetings! Could someone please help me make this code function properly? I am attempting to display the DIV (slidingDiv) and navigate to the selected ANCHOR (#anchor-01 + #anchor-02 + #anchor-03)... However, the code currently only allows me to go to the ...

Adjusting the array of buttons with various functions within the Header component

I am looking to create a customizable Header component with different sets of buttons that trigger various functions. For example, on the home page, the buttons could be "visit about page" and "trigger vuex action A", while on the about page they could be ...

Creating dynamic templates for table rows in AngularJS directives

Is it possible to dynamically load an AngularJS Directive templateUrl while working within a table? In my scenario, I have the following HTML structure where I am repeating a tr element with a fw-rule directive: <tbody> <tr ng-repeat="rule in ...

Fill the second dropdown menu options based on the selection made in the first dropdown menu

I need assistance with dynamically populating my second drop-down menu based on the selection made in the first drop-down. Here are the steps I've taken so far: form.php - Utilizing javascript, I have set up a function to call getgeneral.php. The se ...

JavaScript: abbreviated way to selectively append an element to an array

Currently, I am in the process of creating a Mocha test for a server at my workplace. When dealing with customer information, I receive two potential phone numbers, with at least one being defined. var homePhone = result.homePhone; var altPhone = ...

Verify key in JSON object using org.json.simple library in Java

Is there a way to convert a key into a JSONObject using the org.json.simple library? I've tried a few methods but encountered errors in each attempt. 1st Attempt JSONObject name1 = (JSONObject) jsonObject.get(key); Error: cannot convert java.lan ...

Struggling to properly test the functionality of my NgForm call in Angular2+

I've been trying to test the login functionality by inputting username and password in an NgForm, but I keep encountering unsuccessful attempts. Is there a vital step that I may be overlooking? Currently, I'm facing this error message: Chrome 6 ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

The functionality of cloning in jQuery may encounter an issue where the text field remains enabled if the user selects an option labeled "other

Currently, I am working on a jQuery clone with my existing code and everything is functioning well. In the first scenario, if the user selects other from the dropdown menu, the text field becomes enabled. In the second scenario, when the user clicks ...

How can you set an input field to be initially read-only and then allow editing upon clicking a button using Vue.js?

//I have two divs that need to be set as readonly initially. When an edit button is clicked, I want to remove the readonly attribute and make them editable. <div> <input type="text" placeholder="<a href="/cdn-cgi/l/email-protection ...

When attempting to change a Component's name from a string to its Component type in Angular 9, an error is thrown stating that the passed-in type is

When working with Template HTML: <ng-container *ngComponentOutlet="getComponent(item.component); injector: dynamicComponentInjector"> </ng-container> In the .ts file (THIS WORKS) getComponent(component){ return component; //compo ...

I'm encountering an issue with my React master component not being able to locate the

I am having trouble importing a component in my APP.js file. I have been attempting to bring MainComponent into the app.js component, but I am facing difficulties in fetching the component. Any assistance in resolving this issue would be greatly apprecia ...

Issue with Browsersync causing task to malfunction in Gulp 4

Gulp Local v4.0.2, CLI v2.3.0 Browsersync v2.26.13 gulpfile.js: 'use strict' const gulp = require('gulp') const concat = require('gulp-concat') const babel = require('gulp-babel') const uglify ...

Tips for preventing HTML ID clashes while integrating with the Document Object Model of external websites

When incorporating additional HTML elements into a webpage using Javascript or jQuery, along with external CSS declarations, it is important to avoid conflicts with existing IDs and class names already present on the page. This could lead to issues if ther ...

How to transform a hyperlink into a clickable element within an absolutely positioned container

I'm currently working on a photo gallery project and using magnific popup to create it. However, I ran into an issue with the hover event on the images that displays an icon when it's hovered over, indicating that it can be clicked to view more. ...

What is the process for extracting information from JSON data that is not in

Attempting to extract data from a local .json file by utilizing StreamReader and Json.NET. The json content and code snippet are as follows: Contents of .json file: {"rate":50,"information":{"height":70,"ssn":43,"name":"andrew"}} using (v ...

JSON Scheme - Mandatory Array Declaration

When working with JSON formatting, certain objects may need to be converted into an array. The JSON field can come in three different ways: The first scenario is working perfectly. "Deliverytypes": { "DeliveryType": [ ...

The function .play() cannot be executed on document.getElementById(...) - it is not a

There is an error in the console indicating that document.getElementById(...).play is not a valid function. import React from 'react'; const musicComponent=(props)=>{ const style={background:props.color} return( <div classN ...

react-native-track-player failing to play song requested from Express server

I set up an expressjs server with a 'songs' route that serves .mp3 files. Here is the code for the Songs Route: import express from "express" const path = require("path") const router = express.Router() ... router.get(" ...

Transform JSON dictionary into a row within a Pandas DataFrame

I have retrieved JSON data from a URL, resulting in a dictionary. How can I restructure this dictionary so that each key becomes a column and the timestamp acts as the row index for each entry gathered from the URL? Below is the raw data obtained: with u ...