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

Tips for successfully sending an array via an XMLHttp Get request

I am currently working on a project where I need to utilize all the values from an array in my GET request. The code snippet below outlines my approach: function executeRequest(){ let data = ['value1', 'value2', 'value3'] ...

How can I locally store 3D models and textures using three.js?

Currently working on a game using three.js, where each game level is on a different page. However, when transitioning from one level to another, the browser reloads the page which can be quite slow. Is there a way to store 3D models locally so they don&apo ...

Removing items in vue.js

I'm currently in the process of learning Vue.js. This is my first attempt at creating a small to-do application, and I am encountering issues with deleting each individual task upon clicking. Despite watching multiple YouTube tutorials, I have not bee ...

What is the best way to export image paths using require() from a single index.js file in a React Native project?

I am looking for a way to efficiently export all images from a single file named index.js, so that in the future, if I need to change the path of an image, I only have to make changes in one file. For example: export {default as avatar} from './avata ...

Have I potentially compromised my project by executing the command `npm audit fix --force`?

While working on a React project using Vite, everything was going smoothly. I decided to incorporate some charts and came across the recharts package, which I found quite appealing. So, I added it to my project using the command npm i recharts. After runn ...

Can image data be extracted from a canvas without needing to physically render the canvas?

I am currently working on an Angular application that utilizes Chart.js to create dynamic charts in various views. Additionally, the application has the capability to export data to a PDF format using the PDFMake JavaScript library, which is a basic tool a ...

Nuxt has the ability to display the object itself, however, it cannot render its

I am using a directus API to fetch data, which is returned in an array of objects. I can render the array or an object from it, but not when trying to access a property of the object <template> <div class="grid grid-cols-2 gap-6 mt-6&quo ...

Matching queries precisely in MongoDB

I developed an Express.js API with MongoDB integration that filters products based on a filter property. The issue I am facing is ensuring that the API output exactly matches the filter property criteria. Currently, if Product A has [{name: 'a', ...

Planes in Three.js that are overflowing may have their opacity adjusted

My current challenge involves aligning two planes in the same (or closest possible) position. When two planes made of different materials and colors occupy the same space, depending on the camera angle and view perspective, the front plane's opacity ...

The code encountered an error because it was unable to access the property 'style' of an undefined element on line 13 of the script

Why is it not recognizing styles and showing an error? All paths seem correct, styles and scripts are connected, but it's either not reading them at all (styles) or displaying an error. Here is the html, javascript, css code. How can this error be fix ...

Implementing React and Material UI: Maximizing Vertical Space Usage for a Box Component

Currently, I am working on a web application using React combined with Material UI. Within my code snippet below, you will see three Box components in play. Box 1 and Box 3 have specific heights set, but I am looking for a way to make Box 2 occupy the re ...

Functionality of Ajax: Data fields containing numerous values

I'm confused about the data fields in the ajax function. Typically, the syntax for an ajax function looks something like this: $.ajax({ url: "/aaa/bbb/ccc", method: "SomeMethod", data: someData, success: function (res ...

Issue encountered when utilizing ngResource in factory: unable to choose JSON index

ngResource in a factory is functioning properly, but unfortunately, it is only able to select the index of the JSON. However, it is also possible to bind the same variable $scope.resultItems. The console log appears as follows ...

What is the best way to link JSON array information to the HTML using MVC?

I'm currently working with MVC5 and I am trying to populate a div element with data using the .html(data) method. .done(function (data) { var result = $.parseJSON(data); $("#mydata").html(result); }); <div id="mydata"></div> Th ...

Combining and visualizing multiple datetime series in Highcharts

Is there a way to overlay two datetime x-axes that have different date ranges but the same number of data points? I want point index x from series 1 to line up with point index x from series 2. I attempted to do this by using two x-axes, one of which is h ...

If the first <select> option is chosen, then a second <select> validation is necessary

Is it possible to make the second selection required for validation only if the 'yes' option is selected in the first one? <div class="form-group" ng-class="{ 'has-error' : articleEditForm.pnp.$invalid && !articleEditForm.pn ...

The call stack size has reached its maximum limit due to running 2 Collection.find commands

I've encountered a Maximum call stack size exceeded exception in my Chrome console while working with Angular2 and Meteor. This issue started after I added the following code to my client side: var userChannelsId = UserChannels.find({idUser: Meteor.u ...

Encountering difficulties setting cookies within the app router in Next.js

I've been diving into next.js and I'm trying to figure out how to set a cookie using the code below. However, I'm encountering an error: "Unhandled Runtime Error. Error: Cookies can only be modified in a Server Action or Route Handler." I ...

Guidelines for sending an array from a Laravel Controller through AJAX and generating a button based on the received data

Before making a selection, I click on the Color button: <form class="form form-variant"> {{ csrf_field() }} <button type="submit" class="btn btn-success che ...

Adding CSS styling to a particular component within your Vue application using Vuetify JS

Imagine having a Test.vue file containing 2 v-text-field components. I'm looking to style only the first text field using CSS. Test.vue <template> <div class="test"> <v-text-field></v-text-field> <v-tex ...