When attempting to log an AJAX/JSON request, the console.log statement is displaying 'undefined'

Being new to AJAX, I have encountered an issue that I believe others may have faced as well. Despite numerous attempts and extensive research, I am unable to find a solution to this error. I am confident that it is something simple. Any help would be greatly appreciated.

// defining variable for JSON request
var request = new XMLHttpRequest();

// initiating GET request for specified JSON URL
request.open('GET', 'http://api.fixer.io/latest');
ourRequest.onload = function () {
    var data = JSON.parse(request.responseText);
    console.log(data[1]);
};

request.send();

Answer №1

ourData is actually a JavaScript object and not an array.

If you are trying to access the date using ourData[1], you should instead use either ourData.date or ourData['date']

// Defining a variable for our JSON request
var ourRequest = new XMLHttpRequest();

// Making a GET request to retrieve data from a specified JSON link
ourRequest.open('GET', 'https://api.fixer.io/latest');
ourRequest.onload = function () {
    var ourData = JSON.parse(ourRequest.responseText);
    console.log(ourData['date']);
    console.log(ourData.date);
};

ourRequest.send();

Answer №2

To handle the response in Json format, you can utilize the provided code snippet and customize it as needed:

var request = new XMLHttpRequest();

// Make a GET request to the specified JSON link
request.open('GET', 'http://api.fixer.io/latest');
request.onload = function () {
    var data = JSON.parse(request.responseText);
    console.log(data['date']);
    console.log(data.date); // Alternatively, this format can be used
    console.log(data['base']);
    console.log(data.base);
    console.log(data['rates']);
    console.log(data.rates);
    console.log(data['rates']['AUD']);
    console.log(data['rates'].AUD);
};

request.send();

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

Utilizing PHP Variables in Jquery Ajax Success Response

I have a webpage that displays a list of routes. When a user clicks on a route, an AJAX request is sent to save the selected route in the database. On the same page, in a different tab, I am running a query to fetch related information about the selected ...

Add a preventDefault event listener to a submit button that triggers a specific function

$(function() { $('#login').submit(function(e){ preventSubmission(); e.preventDefault(); }); }); function preventSubmission() { $('#btnLogin').attr('disabled','disabled'); $("#btnLogi ...

Issue with Ionic Framework Typescript: `this` variables cannot be accessed from callback functions

Is it possible for a callback function to access the variables within this? I am currently working with d3.request and ionic 3. I can successfully make a REST call using d3.request, but I am facing difficulty when trying to assign the response to my this. ...

Retrieve information from a MySQL database and integrate it into a different application

This php script is used to generate a table with a "book" button next to each row. The goal is to extract the values of "phase" and "site" from the specific row where the "book" button is clicked, and transfer them to another form (in "restricted.php") fo ...

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

Creating a tool that produces numerous dynamic identifiers following a specific format

I am working on a function to create multiple dynamic IDs with a specific pattern. How can I achieve this? followup: Vue.js: How to generate multiple dynamic IDs with a defined pattern Details: I am developing an interactive school test application. Whe ...

Mall magnitude miscalculation

I am currently experiencing an issue with Galleria and the Flickr plugin. Some images are displaying correctly, while others appear scaled and parts of them are cut off. How can I fix this problem? Below is the HTML code for the Galleria gallery on my web ...

Struggling with implementing a conditional template component within an AngularJS directive

As a Java/Python developer, I found myself working on an AngularJS project recently. While most concepts were easy to grasp, some of the syntax and functionality still elude me. The code I have handles login/logout functionality. If the user is logged in ...

Uncertain about troubleshooting the `uid: prismicDocument.uid ?? void 0` error on a Prismic and Next.js website?

Currently, I am working on a Next.js project integrated with the Prismic CMS. The website runs smoothly in my local environment, however, after some recent updates to the content, I encountered the following error during production builds: 2:42:19 PM: /opt ...

Display the list items within a div only if the height is lower than a separate div

I have a scenario where I have two divs named left and right. The left div contains a list of bullets (li elements) and is floated to the left, while the right div has text and HTML content. At times, either the left or the right div may be taller than the ...

How can I incorporate a vertical line divider and a legend into a curved box using HTML and CSS?

https://i.sstatic.net/dj4zb.png I have this image that I need to divide into three sections with a legend at the top, similar to the image shown. So far, this is the code I have, but I'm struggling with creating the vertical line, adding space betwe ...

Guide to showcasing console output on a Web Server

Apologies if this question is not the most suitable for this platform. I recently set up Pure-FTPd service on a CentOS server. To check current connections, I use the command pure-ftpwho, which gives me the following output: +------+---------+-------+---- ...

Failed to set Firebase data: The first argument provided contains an undefined property

When it comes to creating an event, here's my approach: export const handleEventCreation = ({ title, time, location }) => { const newEventKey = firebase.database().ref('/events').push().key; const updates = {}; const eventDetails ...

Ways to Determine if the Content in the CKEditor has Been Altered

Is there a way to detect changes in the content of CKEditor? I want to trigger a JavaScript function every time the content is updated. ...

Creating a series of image files from CSS and Javascript animations using Selenium in Python

Looking to convert custom CSS3/Javascript animations into PNG files on the server side and then combine them into a single video file? I found an interesting solution using PhantomJS here. As I am not very familiar with Selenium, adapting it for use with S ...

Refreshing web pages using AJAX

I currently have an application that includes a search feature where users can look up items in the database. The search functionality is working well with AJAX, but I'm now looking to incorporate this AJAX functionality into my pagination system. Spe ...

What advantages does $sce or Strict Contextual Escaping provide in AngularJS, and why is it unnecessary for React?

I find it perplexing that I am unable to fully grasp the true value of utilizing SCE in AngularJS (even after reviewing the documentation) when it comes to security benefits. It leaves me wondering why React does not require SCE. So, to summarize my quest ...

What strategies work best for managing jQuery ajax calls that run asynchronously?

Currently, I am working on a project that heavily relies on client-side jQuery and JavaScript. However, I have encountered difficulties in getting one of the screens to function properly. One particular function in my code looks like this: function init{ ...

The inner workings of GSON unraveled

Working with GSON on my current project has been truly impressive. I am fascinated by its ability to effortlessly convert objects into JSON and vice versa. Although I have read the Google user guide, I am still curious about the internal workings of GSON ...

I am struggling to set up angular-localstorage4

I have been following the instructions in the provided link: angular-localstorage4 When attempting to import WebStorageModule and LocalStorageService from angular-localstorage, I encounter an error in the console even though the compilation is successful. ...