What is the correct way to fetch JSON data from a remote server using pure JavaScript?

I'm receiving JSON data from a remote server at openweathermap.org. Can anyone help me identify issues with my code? Here is an example of the server's response here

var getWeatherJSON = function (city) {
    var httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); 
    var jsonText;
    httpRequest.onreadystatechange = function () {
        //====jsonText after getting respons equals null====
        jsonText = httpRequest.readyState == 4 && httpRequest.status == 200 ? httpRequest.responseText : null;
    }
    httpRequest.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + city, true);
    httpRequest.send();
    return jsonText;
}

Answer №1

It is important to note that the jsonText cannot be directly returned from the getWeatherJSON function or the onreadystatechange function. Instead, you need to utilize this data within a separate function that can handle it appropriately. For example:

httpRequest.onreadystatechange = function () {
  //====jsonText after getting response equals null====
  jsonText = httpRequest.readyState == 4 && httpRequest.status == 200 ? httpRequest.responseText : null;
  callbackFunction(jsonText);
}

Answer №2

Switching "true" to "false" can make a difference. It actually works!

httpRequest.open("GET", "" + city, false);

If you opt for "true," it becomes an Asynchronous request, which means you need to utilize a "callback function."

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 ensure that the code only runs if the promise has been successfully fulfilled

In my NodeJS project, I am leveraging promises to ensure that the server stops running if certain functions do not meet the required conditions. Currently, the server halts as intended, but I also want to include a console log message when the promises are ...

Using React and Typescript, implement an Ant Design Table that includes a Dropdown column. This column should pass

Next Row: { title: "Adventure", render: (item: ToDoItem) => { //<- this item return ( <Dropdown overlay={menu}> <Button> Explore <DownOutlined /> </Button> </Dropdown&g ...

Infinite dice roller for a six-sided die

Looking for assistance with a School JavaScript assignment focusing on creating a 6-sided dice roller program? Need some guidance on how to approach this task? The program should allow users to choose how many dices to roll, ranging from 1 to 5. The sum o ...

Having trouble with the Jquery click event not functioning on an interactive image map in Chrome browser

I currently have an interactive image-map embedded on my website. Here is the HTML code: <div id="italy-map" class="affiancato verticalmenteAllineato"> <div id="region-map"> <img src="./Immagini/transparent.gif" title="Click on ...

Exploring Dynamic Datatype for Deserializing JSON in WinRT

Recently, I attempted to deserialize JSON data using the JSON.Net API with a dynamic datatype. After extensive research on various forums, I discovered that it is indeed possible to achieve this in WinRT. An example of JSON content could be: string json ...

Receiving messages in AngularJS with the help of Strophe.js

My XMPP client in AngularJS, inspired by this stackoverflow link. <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d282e382f1d282e382f7331323e3c31">[email protected]</a> can send messages successfully, but <a hr ...

How to send arguments to a callback function in Next.JS

Here's the code snippet I'm working with: import Router from "next/router"; import React from "react"; export default function MainIndex() { return (<React.Fragment> <h1>Main Index Page</h1> ...

Getting the final element in a MySQL JSON array: Tips and tricks

After finally upgrading to MySQL 5.7, I've been exploring the new JSON functions and they are quite impressive! I encountered a scenario where I needed to retrieve the last element in a JSON array. It's simple when you know the ordinal position ...

Searching Firebase by using comparison operators on various fields

const FindFiis = async () => { const data: any[] = []; // Firebase query with inequalities on different fields to retrieve docs. // Objective: Select documents where dividendYield is between 8 and 20 and pvp is less than or equal to 1. ...

Unpacking key-value pairs from a JSON array in PHP and restructuring the data

Looking for suggestions on how to transform the JSON structure shown below: $jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"}, {"Level":"399.2023%","Product":"Coffee","Temperature":"34"}, {"Level":"109.2023%","Product ...

Unable to activate Knockout data-bind using jQuery

I'm developing a plugin using jQuery and knockout.js. Currently, I have a scenario where I need to manipulate radio buttons with knockout data-bindings. However, I've encountered an issue when trying to uncheck a radio button by clicking another ...

Formik's handleChange function is causing an error stating "TypeError: null is not an object (evaluating '_a.type')" specifically when used in conjunction with the onChange event in DateInput

When using the handleChange function from Formik with the DateInput component in "semantic-ui-calendar-react", I encountered an error upon selecting a date. https://i.stack.imgur.com/l56hP.jpg shows the console output related to the error. AddWishlistFor ...

Controller function failing to trigger

I'm new to asking questions, so if I've made a mistake, please let me know. I've searched for an answer here but couldn't find one. Any help would be greatly appreciated. I'm attempting to load a list of "Countries" using a contro ...

Utilizing third party (jQuery) with AngularJS $compile

Currently, I am integrating angularjs into a website that is already using jquery to load content asynchronously. The content is loaded and then appended to the DOM using jQuery instead of AngularJS. Here is an example of what I have: function loadConte ...

Unusual behavior observed when filling a Spinner from a database source

I am facing an issue while trying to populate a spinner from a MySQL database using JSON. The data is successfully exported, but the app crashes when I click on the Spinner to show the dropdown menu. The JSON output from the database can be viewed here. ...

Limiting ng-repeat in AngularJS when the last item on the object is reached

I have a large object being repeated using ng-repeat, and it runs smoothly on Chrome and Opera. However, when it comes to browsers like Mozilla and IE, the performance is very slow. I tried implementing pagination, which helped speed things up, but ideally ...

Implementing search and filtering functionality in a REST API using nodejs and express: A step-by-step guide

Currently, I am delving into the world of Node and Express by constructing a REST API. Instead of utilizing a database to store data, I am experimenting with doing everything in-memory. Imagine that I have an array of users: var users = [{"id": "1", "fir ...

Highcharts: Limiting the yAxis values to a maximum of two decimal places

Here is the code for my graph, which retrieves data from a PHP page and adds some series: $('#grafico_1').highcharts({ chart: { type: 'line', zoomType: 'xy', animation : false, events: { selection: functi ...

Navigating Redirects using axios in the Browser

Is there a way to work with redirects in axios to capture the redirected URL in the browser when making an API call? I am looking to retrieve the redirected URL through a GET request. ...

How can I utilize jQuery to add tags in a box?

I have an idea for a feature similar to the Stack Overflow tag insert. My goal is to have a box where I can type in a tag, click 'Add', and see it appear above. Additionally, I want this action to update an array called 'SelectedTags'. ...