I faced a challenge when attempting to retrieve a JSON object with an XMLHttpRequest, causing the result to be an

My attempts to Fetch and Parse a JSON Object using XMLHttpRequest in Javascript are always unsuccessful, resulting in an empty quotation...


            function fetchAndParseJSON(target = null)
            {
                var response_data = [];
                var target_url = target;
                var xhr = new XMLHttpRequest();
                xhr.open('GET', target_url, true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.send();
                xhr.addEventListener("readystatechange", function ()
                {
                  if(xhr.readyState === 4)
                  {
                     if(xhr.status >= 200 && xhr.status < 304)
                     {
                        response_data += xhr.response;
                     }
                     else
                     {
                        response_data += $.getJSON(target_url);
                        console.log('[XHR-DEBUG]: Unexpected HTTP response code: ' + xhr.status + ': ' + xhr.statusText + '(' + target_url + ')');            
                     }
                  }
                });
                return JSON.parse(JSON.stringify((typeof response_data === 'undefined' || response_data === null || response_data.toString().split(',').length <= 1 ? xhr.response : response_data)));
            }

Usage:

   fetchAndParseJSON('localhost/logs.json');

Expected output:


   ["John eaten the cake","Stackoverflow is awesome"]

Result obtained:

   ""

Answer №1

The issue lies in the usage of asynchronous XMLHttpRequest. The problem arises at this particular line of code:

return JSON.parse(JSON.stringify((typeof response_data === 'undefined' || response_data === null || response_data.toString().split(',').length <= 1 ? xhr.response : response_data)));

This line is situated outside the event listener, causing data unavailability when executed.

To resolve this, you can opt for synchronous XMLHttpRequest (though not recommended):

xhr.open('GET',target_url,false)

Alternatively, you could utilize async/await functionality like so:

async function getJSON(target = null) {
    var response_data = [];
    var target_url = target;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', target_url, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    await new Promise((resolve,reject)=>{
        xhr.addEventListener("readystatechange", function () {
            if(xhr.readyState === 4) {
                if(xhr.status >= 200 && xhr.status < 304) {
                    response_data.push(xhr.response);
                 } else {
                    response_data.push(await getJSON(target_url));
                    console.log('[XHR-DEBUG]: Unexpected HTTP response code: ' + xhr.status + ': ' + xhr.statusText + '(' + target_url + ')');            
                }
                resolve()
            }
        });
        xhr.send()
    });
    
    return JSON.parse(JSON.stringify((typeof response_data === 'undefined' || response_data === null || response_data.length <= 1 )? xhr.response : response_data));
}

For further reference, check out these resources:

Async function
Promise
Await operator

I trust that this information proves useful to you!

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

loading the css and javascript files based on the specified prop parameter

In the process of working on a ReactJS file that utilizes the react-ace library, I currently have the following code implemented. import React, { Component } from 'react'; import 'brace/mode/html'; import 'brace/theme/monokai&apos ...

Perform Function Again

Recently, I came across some code for a tesseract ocr from Google that seemed to be functioning well. However, I encountered an issue where it would work fine the first time I input a URL, but on the second run, it wouldn't work without a manual page ...

Steps to display a div on top of a background image

Here is a visual representation of my design for better understanding: I am currently working on developing the central content that overlays the image. However, when I insert divs with background colors into my HTML to test their placement, I do not see ...

Retrieving the nth character from a given string

How can I extract every 3rd character from a given string, such as the word GOOGLE? I have attempted to accomplish this using JavaScript, but I am unsure of what code to include after the 'if' statement. function getNthElements(string) { v ...

ESLint is reminding you that the `parserOptions.project` setting must be configured to reference the tsconfig.json files specific to your

Within my NX Workspace, I am developing a NestJS-Angular project. Upon running nx lint, an error is triggered with the following message: Error: A lint rule requiring the TypeScript type-checker to be fully available has been attempted, but `parserOptions. ...

An established connection was abruptly terminated by the software on your end, resulting in ERROR Errno::ECONNABORTED

Attempting to make a post request via jQuery to a Rails controller, using the following post request: $(document).ready( function() { $("#LogIn").submit(function() { var myemail = $('input[name=Email]').val(); ...

Interested in learning about conducting a length check validation within specified conditions utilizing the Json Schema Validator?

I have a JSON schema structure that looks like this. { "$schema": "https://json-schema.org/draft/2019-09/schema", "description": "My sample Json", "type": "object", "properties": ...

Determine the number of JSON elements in a SQL query

I am working with these json strings: [{"count": 9, "name": "fixkit", "label": "Repair Kit"}, {"count": 1, "name": "phone", "label": "Telefoon"}] [{"count": 3, "name": "phone", "label": "Telefoon"}] [{"count": 5, "name": "kunststof", "label": "Kunststof"} ...

Alter the hue within Google Chart

I'm working on customizing a Google Bar Chart with Material design and running into an issue with changing the background color. I've tried using backgroundColor and fill identifiers in the options, but the inner area of the chart where the data ...

Using a Javascript while loop to iterate through an array and display the elements in the .innerHTML property

As a newcomer to Javascript, I am in the process of teaching myself. My current task is to develop a function that will display each element of the array AmericanCars with a space between them. I have successfully been able to show an individual element u ...

Javascript: Executing a interval, delay, and another interval

My challenge is to reveal a list of elements one after another using setInterval for 5 seconds. However, I want to introduce a 60-second timeout after the 7th element and then continue the interval without repeating the timeout for every 7th element. Here ...

Utilizing Java 14 records in conjunction with the org.json library

Recently, I was attempting to create a new JSON object using the org.json library. However, I encountered an issue when working with Java 14 records. After calling: String json = new JSONObject(new Order("", "Albert", "GOOGL", "SELL", 97.9, 90L)).toString ...

Is there a way to extract information from my JSON file and display it on my website?

My aim is to populate my HTML page with data from a JSON file. Approach I created a JavaScript file: update-info.js In this file, I used an AJAX call to retrieve data from my JSON file data.json If the request is successful, I utilized jQuery's .htm ...

Guide on decoding JSON data in Java: retrieving JSON data from a local server and displaying its contents

My current project involves working on a basic example of encoding and decoding JSON using Java. The goal is to send signup page details to a JavaScript function, which then encodes these values into JSON format before sending them to a servlet. While I h ...

Transfer information from a single form and distribute it across multiple forms with the help of jQuery or Javascript

Form1 has a variety of input fields including text, select, radio, and textarea. At the bottom there is a button labeled "copy" that allows users to copy data from all the fields in Form1. In different pages, I have three to four other forms with input fi ...

Transforming JArray into an Object with specific attributes

I am faced with the challenge of converting a JArray into an Object using Attributes because I cannot modify the existing call in a decoupled class: var message = JsonConvert.DeserializeObject(e.Message, messageType) The JSON data to be converted is as f ...

AngularJS - Always keep an eye on a group of items

Looking to create a custom watcher for a collection within my application, I initially believed that Angular would have all the necessary tools at my disposal. I had access to $watch, both shallow and deep, as well as $watchCollection. A $digest cycle was ...

Extracting information from multiple JSON arrays in C#

Searching for statistics in this Json Code is my goal: { "summonerId": 32033681, "modifyDate": 1403658807000, "champions": [{ "id": 40, "stats": { "totalSessionsPlayed": 1, "totalSessionsLost": 0, ...

An error has occurred: The transport specified is invalid and must be an object containing a log method

Issue: I am facing a problem while trying to run the node server.js file to execute a port listening http_server. It seems like the code is not working properly. Can someone please help me resolve this issue? var socket = require('socket.io'), ...

Error: Module not located in Custom NPM UI Library catalog

I have recently developed an NPM package to store all of my UI components that I have created over the past few years. After uploading the package onto NPM, I encountered an issue when trying to use a button in another project. The error message "Module no ...