Save information in JSON format inside a variable using pure JavaScript

I'm having trouble retrieving data from a JSON file using JavaScript. The console is showing the result as undefined.

The GET request seems to be successful and the function is executing, but I'm unable to access the response data.

function fetchDataFromJSON(url) {
    var request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.setRequestHeader("Content-type", "application/json");

    request.onreadystatechange = function() {
        if(request.readyState == 4 && request.status == 200){
            return JSON.parse(request.responseText);
        }
    };

    request.send();
}

var jsonData = fetchDataFromJSON('questions.json');

console.log(jsonData); //undefined

http://codepen.io/gsg/pen/LEEeMg

Answer №1

Keep in mind the nature of this function—it operates asynchronously. Consider implementing a callback approach for potentially better results.

function AJAX_JSON_Req(url, cb) {
    var request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.setRequestHeader("Content-type", "application/json");

    request.onreadystatechange = function() {
        if(request.readyState == 4 && request.status == 200){
            cb(JSON.parse(request.responseText));
        }
    };

    request.send();
}

AJAX_JSON_Req('questions.json', function (q) {
  console.log(q);
});

Answer №2

AJAX is short for Asynchronous JavaScript and XML.

This means that the data is not available immediately when your function completes.

onreadystatechange serves as an event listener, functioning as a non-standard variation of:

AJAX_request.addEventListener("readystatechange", function () {
    // state has changed
});

An easy solution would be to utilize a callback, like so:

AJAX_JSON_Request("questions.json", function (response) {
    console.log(response);
});

Then you can have:

AJAX_request.addEventListener("readystatechange", function () {
    // check if state == 4
    callback(JSON.parse(AJAX_request.responseText));
});

One common method for handling asynchronous operations is through the use of Promises, which helps in avoiding the chaos of nested callbacks.

This leads to something along these lines:

AJAX_JSON_Request("questions.json").done(function (response) {
    console.log(response);
});

Promises are not inherently supported yet; however, you can create your own implementation or rely on established frameworks.

Now,

AJAX_JSON_Request("questions.json")
generates something: a Promise. The value may not be accessible instantly, but the promise ensures that you will receive it eventually.

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

Adjust the styling with jQuery according to the selected value from the dropdown menu

Check out this Fiddle I have a jQuery script that is supposed to change the style of an input box to display:block if the selected value is "<>" (Between). However, currently it is changing the css for all selected items instead of just the target i ...

Setting a global variable in the JavaScript code below

Is there a way to make the modal variable global by setting it as var modal = $("#modal"); ? The code snippet below includes the modal variable and is not functioning properly. It needs to work correctly in order to display: "Hello name, You have signed u ...

Learn the process of retrieving a file from server.js and showcasing it on an HTML page

I am currently developing a YouTube video downloader using express, HTML, and JavaScript, with plans to transition to Vue.js in the future. Here is a snippet of my code: Index.html <!DOCTYPE html> <html lang="en"> <head> & ...

Displaying the scope in HTML from a custom Angular directive: A step-by-step guide

Just getting started with angular js and I have a question. Is there a way to show the values of e.width and e.height in an HTML document? Can I utilize the scope within this context? .directive( "cropping", [function ($scope) { return { rest ...

Converting JavaScript array within a JSON string into a Golang map

I encountered an issue with an API that returns a JSON where one of the elements is supposed to be an array but is wrapped in quotation marks. This is causing the "encoding/json" package to not recognize that element as an array. When I attempt to access ...

Transmit information from javascript to the server

I am currently working on an ASP.NET MVC web application and have a query: If I have a strongly typed view and I submit it, the object (of the strongly type) will be filled and sent to the server. But what if one of the properties of the strongly typed i ...

Euler 13: Surprising outcome when attempting to combine several String variables

I'm currently working on a challenging problem found on euler: here Large sum Problem 13 In this problem, the task is to determine the first ten digits of the total sum when adding up one-hundred 50-digit numbers. 37107287533902102798797998220837590 ...

Creating a blank grid using ng-repeat in angularJS

I'm attempting to create an empty grid using angularJS, but I've only been working with it for 2 days so I'm not very experienced. This is what I have come up with so far: <!doctype html> <html ng-app> <head> < ...

What is the best way to manipulate the positioning and rotation of the main object?

https://i.sstatic.net/HSRZz.png https://i.sstatic.net/1dggf.png After developing a toolbox capable of rotating and repositioning a mesh with an axis in the middle, I ran into an issue where separating rotation and position caused the position to revert to ...

Scrolling with Jquery window.scrollTo results in the page becoming unresponsive

I'm currently revamping a website that features a header with 100% screen height, but I need it to shrink down to 0px when a user starts scrolling. The issue I'm facing is that once the header shrinks to 0px, the page content ends up slightly abo ...

No options displayed in AngularJS select2 dropdown

I have implemented select2 in my code following the instructions provided at https://github.com/angular-ui/ui-select2 <div ng-controller="sampleController> <select ui-select2 ng-model="select2" data-placeholder="Pick a number"> < ...

What is the most effective method for transferring an error message from the server backend to the vue frontend?

I'm currently working on implementing error handling for a Vue/Vuetify application. The challenge I'm facing involves using external pagination for a datatable that connects to an API with rate limiting restrictions. If users exceed the limit, I ...

Troubleshooting alignment problems with a responsive gallery (Bootstrap-gallery & justifyGallery)

Looking to showcase a gallery of images using jquery-justifyGallery and bootstrap-gallery. Want to display 4 images in a row, but running into issues when trying to display 5 images where the last image in the row ends up with a larger width. Bootstrap has ...

Attempting to extract the text within a table row cell by clicking on the cell directly following it

I am trying to extract the data from a table row when I click on a specific div within that row HTML: <td class="ms-cellstyle ms-vb2">10</td> <td class="ms-cellstyle ms-vb2"> <div class="ms-chkmark-container"> <div ...

Detecting when the user exits AR mode in A-Frame

In my A-Frame project under development, users are given the option to choose between playing the game in AR mode or traditional non-AR 3D mode. If a user unexpectedly leaves AR mode (by exiting fullscreen, for example), it is crucial for us to detect thi ...

CSS - Achieving full width on hover even when the element has a specified width setting

I am encountering an issue with my CSS. Although I have successfully centered everything, I am facing a problem with the hover effect in CSS. Whenever I apply the active class or hover over an li element, the background color expands to 100%. Additionally, ...

Module request: How can I save the gathered cookies as a variable?

library: https://www.npmjs.com/package/request I am attempting to simultaneously log in with multiple accounts on a website. To manage each session effectively, I plan to create an object where I will store the cookies associated with each account. Now, ...

Comparing ID numbers and adding them together before storing them in a new array

In order to consolidate numbers with the same sequence ID and store the total sum in a new array named 'final', follow the steps below: INPUT => $scope.initial = [{seq:11, name:'ABC', number:20}, {seq:11, name:&ap ...

Sending documents to a printer directly from a Rails application

Is there a library or gem in Rails that can be used to print the contents of a web page directly onto paper? I am curious if it's possible to specify only a specific part of the page, such as a div, for printing. Any guidance, advice, or tutorial link ...

Adding elements to a JSON array in Javascript

Seeking assistance on updating a JSON array. var updatedData = { updatedValues: [{a:0,b:0}]}; updatedData.updatedValues.push({c:0}); This will result in: {updatedValues: [{a: 0, b: 0}, {c: 0}]} How can I modify the code so that "c" becomes part of ...