Having difficulty retrieving a response from an API using JavaScript

I have been trying to capture the response using the code below, but unfortunately, I am not able to retrieve it. Can someone please help me and let me know what I might be missing here?

function getData() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://demo8951713.mockable.io/fusionchart', true);
    request.send();
    var response = this.responseText;
    alert(response);
}

getData()

Answer №1

Two challenges are present in your situation.

To begin with, this (as used in your context) does not actually refer to your XHR object.

Furthermore, you are attempting to access the response immediately after sending the request. It is essential to patiently wait until the browser has received and processed the response!

request.addEventListener("load", function () {
    var response = this.responseText;
    alert(response);
});

Making this change by moving the code into an event handler will also ensure that this points to the correct object.


After resolving these issues, you may wish to consider returning the value. However, it is important to first consult this question for guidance on handling asynchronous calls.

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

button click event blocked due to unforeseen circumstances

Recently, I've been attempting to change the CSS properties of a div by triggering a click event. However, no matter what I do, it doesn't seem to be working and it's starting to frustrate me. Can anyone shed some light on why this might be ...

Adding a PDF generated from an HTML div to an email using Java

I am looking for a solution to convert the contents of an HTML div tag into a PDF file while preserving its associated CSS. This is essential as I will be using Java on the back-end to send emails, and I need to attach the PDF with the CSS intact when send ...

Manage and maintain database structure with synchronization capabilities

I am tasked with creating a web application that can function offline using Local Storage or IndexedDB. Currently, my server has schema v2 which includes additions such as new tables or fields, while my local app is using schema v1. I am looking for a so ...

Tips for verifying login credentials with MongoDB and Express: Leveraging db.collection().findOne() or .find() functions

I am encountering an issue with a POST request involving user credentials being sent from a Login page to the API Server. The code looks like this: loginUser(creds) { //creds is in the form of { username: bob, password: 123 } var request = { ...

How can I effectively pass an array of objects to an interface in React with Typescript?

In my code, I have defined two interfaces as shown below: export interface TableBoxPropsHeader{ name: string, isIconOnly: boolean } export interface TableBoxProps<T> { headerNames: TableBoxPropsHeader[], // some stuff } I am currently fa ...

Displaying a single result in Angular from JSON without using the ng-repeat filter

Currently, I am working on developing an app to display news updates from a JSON API. The issue I am facing is that loading all the data from the JSON and filtering it using ng-repeat is causing slow performance, as there is a large amount of data. I woul ...

Implementing Vue.js pagination along with making http requests

My table features a pagination-nav component: <b-pagination-nav :link-gen="linkGen" limit="5" :number-of-pages="10" use-router> </b-pagination-nav> To retrieve the table content, I am utilizing the getTrades met ...

What is the best way to set up a backup plan in case a remote GET request is unsuccessful?

Recently diving into iOS development, I find myself enhancing an existing app by incorporating new features. One such addition requires fetching a JSON file from a web server. However, in the event of server unavailability (no internet connection/server do ...

Safari on iOS 11.4 ignoring the 'touch-action: manipulation' property

I ran into an issue while developing a React web app that I want to work seamlessly across different platforms. My goal was to allow users to interact with a div element by double-clicking on desktop and double-tapping on mobile devices. However, when tes ...

The influence on memory when assigning a fresh value to a global variable

Is it safe to reassign global variables with new values without causing memory leaks? Consider the following scenario: gUI = {}; function myFunc1() { gUI.selectedItem = new BigArray(1000); } function myFunc2() { gUI.selectedItem = new BigArray(100 ...

Align the logo at the center of the webpage both vertically and horizontally

Seeking help in centering my logo (775 X 225) both vertically and horizontally on a webpage, with a link "Enter" positioned underneath it. <html> <head> <Title> My Website </Title> <style type="text/css"> //centerlogo CS ...

What could be the reason behind the ineffectiveness of my recently acquired Google Maps API key

For years, I had a function working with the Google API flawlessly. However, after obtaining a new API key, everything seems to have gone haywire. The issue is that there is no output after the `alert(address)` line because the code from `geocoder.geocod ...

Press anywhere outside the slide menu to close it using Javascript

Hey, I've looked around and can't find a solution to my issue. I have a javascript menu that currently requires you to click the X button to close it. I want to be able to simply click anywhere outside the menu to close it instead. <head> ...

Navigate through the page and once you reach a specific point, scroll the element

I'm feeling a bit stuck on how to achieve this particular effect. Imagine a web page where, as a user scrolls down, a specific element responds to the mouse scroll input by appearing to move along with the scrolling motion. Once that element reaches ...

Error encountered with Content Security Policy while utilizing react-stripe

I am currently in the process of developing a React application that incorporates Stripe payments utilizing the @stripe/react-stripe-js (version "^1.9.0") and @stripe/stripe-js (version "^1.32.0") npm packages. While the payments are functioning correctly, ...

What is the best way to switch focus to the next input using jQuery?

Currently, I am implementing the autocomplete feature using jQuery and everything seems to be functioning properly. The only issue I've encountered is with Internet Explorer (IE) - when a user selects an item from the autocomplete list, the focus does ...

How can I replicate the X axis on both ends of a horizontal bar chart using only one dataset in Chart.js version 3.x?

Is there a way to duplicate the X axis ticks on both the bottom and top of a chart? I know there were solutions for older versions of Chartjs, but the options have changed in version 3.x. Previously, you could use something like this: xAxes: [ { ...

Display Further/Hide Fewer every third item using Jquery

I am looking to display only the first 3 list items within each div.content. Then, upon clicking "SHOW MORE", I want to reveal the next 3 items. If the user clicks on "SHOW LESS", I need the display to revert back to showing only the initial 3 list items. ...

Ways to fix the issue of an unspecified user error in authjs

Having trouble with creating a web token using passport LocalStrategy and passport-jwt. I keep getting a user undefined error in auth.js ****401 Unauthorized**** (if (!user) { return res.json(401, { error: 'message' });}). How can I fix this issu ...

HTML Element Split in Two by a Line in the Middle

Greetings to all, after observing for a while I have decided to make my first post here (and just to clarify, I am an electrical engineer, not a programmer). I am in search of creating a unique element in HTML where I can detect clicks on both its upper a ...