The responseText from the Ajax (XMLHttpRequest) call was found to be empty

I've been experimenting with a basic console application that has two main functions: (1.) Sending an asynchronous Ajax request. (2.) Logging the responseText to the console.

To accomplish this, I decided to make an ajax request to openweathermap.org and then parse the responseText into JSON before logging it to the console.

Below is the code I used to achieve this:

var data ;
var url = "http://api.openweathermap.org/data/2.5/weather?id=7535661&APPID=56104080d6cb412468dad1627cb27da6";

var myRequest;

function sendRequest(url){
    myRequest = new XMLHttpRequest();
    myRequest.onreadystatechange= function(){
        if(myRequest.readyState == 4 && myRequest.status== 200){
            data= JSON.parse(myRequest.responseText);
        }
    }

    myRequest.open("GET", url, true );
    myRequest.send();
}

sendRequest(url);
console.log(data);

Every time I run this code, it always returns "undefined".

I would greatly appreciate any assistance on this matter.

Answer №1

Your open() and send() methods are nested inside the onreadystatechange() callback, which means the connection is only opened once the request is completed. To fix this issue, try the following:


var data;
var apiUrl = "http://api.openweathermap.org/data/2.5/weather?id=7535661&APPID=56104080d6cb412468dad1627cb27da6";

var httpRequest;

function makeRequest(url) {
  httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {
      data = JSON.parse(httpRequest.responseText);
      console.log(data);
    }
  }
  httpRequest.open("GET", url, true);
  httpRequest.send();
}

makeRequest(apiUrl);

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

Evaluating operational Angular component - Error: $(...).somename function is not defined

I've encountered an issue while attempting to test my component in Angular. The component itself functions correctly during regular use, but when I try to run the tests using "yarn run test", I receive the following error message: HeadlessChrome 0.0. ...

Challenges with loading multiple iframes on a single page

Having a problem with multiple Iframes on one page - some load randomly on page load while others do not. Links for Iframes have been properly double checked. Looking for suggestions on implementing any jquery code or other method to ensure that all Ifram ...

Using JavaScript to redirect input value for searching a particular webpage

Apologies for any confusion in my code, as I am still learning. I am looking to take an input value and redirect it to perform a search in another help system like Madcap. I have designed a bootstrap page with a search function in the hero banner, and I ...

Processing DataTables in an Asp.Net MVC 4 Environment

I'm currently working on a project that involves using DataTables with an ajax request. The code is functioning, but the execution time ranges from 8-12 seconds which is suboptimal. I need to find a way to optimize this code, particularly the String P ...

Tips for properly escaping JSON data in PHP for seamless parsing with jQuery

My PHP code is responsible for creating a JSON string dynamically and then writing it to a JavaScript string: <? $s = json_encode(array("id" => "1", "name" => 'myn"ame')); ?> <script> <?echo ("var js = '".$s." ...

Verification cannot be completed with the bootstrap modal

I want to implement the use of a bootstrap modal when submitting form data. However, I do not want the form to be submitted if it is empty. Currently, when I try to trigger the bootstrap modal on submit with an empty form, the modal appears instead of prom ...

Using JavaScript to set a form via a parameter in the URL

Is there a way to dynamically change the SetForm based on a parameter in the URL, such as radio.php?land=form2? I tried doing it this way but it doesn't seem to work. However, when I do it manually via the menu, it works. This is my first time attemp ...

What is the best way to locate a document's array item in MongoDB (Mongoose) using its "_id" field?

Here is the schema I'm working with using NestJS and Mongoose: @Schema({ timestamps: true }) export class Listing { @Prop({ type: [{ bidderId: { type: Types.ObjectId, required: true, select: false, ref: User.name, index: true }, ...

JavaScript Discord Bot Unresponsive to Commands

I'm currently working on setting up my first discord bot from a github repository. It successfully connects to discord and logs into the server, but it's not responding to !help commands or any other commands for that matter. The code for the com ...

Tips for setting up OpenLayers demonstrations on a personal server?

Currently, I'm working with an older version of OpenLayers (4.6.2) and find the provided examples extremely helpful for testing and reference purposes. However, the official web page with updated examples only includes the latest version. I am wonder ...

Verifying the Page Load Status in the Browser

I've been spending a lot of time lately trying to find code that will allow me to trigger an action after the browser finishes loading a page. After much searching, I finally came across this piece of code on <script> var everythingLoaded = s ...

What is the process of enabling a concealed input feature?

I have a straightforward script that enables users to input a value into a form. These values are then combined to create a URL, which is used to load a page within an iframe. Everything works fine... but I'm having trouble figuring out how to hide t ...

Minify Magic Dreamweaver Plugin

Does anyone know of a plugin that can minify javascript or css files as they are uploaded using Dreamweaver or similar coding software? For example, if I create a file like functions-global.js, the plugin would upload the original file and also generate a ...

Is there a way to transfer data depending on certain conditions?

I am working on a page where users can choose to email a single file or multiple files. Both options call the same page email.jsp with their corresponding JavaScript functions. In the email.jsp page: String files=null; String url=null; S ...

Utilize Node.js driver to export a Mongo collection into a JSON file

How can I export a MongoDB collection to a JSON format using the Node.js driver and fs.writeFile? ...

The Node script remains active even after all setTimeout functions have completed

I have a script that updates the passwords of all existing Firebase Authentication users we use for testing purposes to reset them to a "clean" state. var admin = require('firebase-admin'); // Input args var jsonKey = process.argv[2]; var proje ...

What is the best way to merge strings and JMESPath queries in order to construct a webhook payload?

I'm currently exploring the use of Cloud Custodian webhooks to generate tagged events in Datadog using the Datadog API. The code snippet below is almost functional, however, the tag for account_id is not being created in Datadog. When examining the b ...

Flag is activated to retrieve the data from the @Input source

@Input() config= []; flag = false; I need to change the flag to true only when I receive data in the config from the @input. Where should I do this? The data in the config is delayed and I am unable to access it in ngOnInit but can get it in ngOnChanges. ...

Dynamic collapsible navigation panels powered by Bootstrap

I am currently working on creating Bootstrap accordions to display supplementary information. However, I have encountered an issue where clicking on one accordion opens all of them simultaneously. Is there a way in HTML, CSS, or JS to prevent this from hap ...

Having trouble with my OpenAI API key not functioning properly within my React application

I've been struggling to implement a chatbot feature into my react app, specifically with generating an LLM-powered response. Despite going through documentation and tutorials, I haven't been successful in resolving the issue. My attempts involve ...