When using XMLHttpRequest() to fetch a JSON file, why do I receive an empty string when I try to log the responseText?

Upon executing console.log(getErrors), the following output is displayed in the console:

XMLHttpRequest {statusText: "", status: 0, responseURL: "", response: "", responseType: ""...}
onabort: null
onerror: null
...
responseText: {"content":[{"id":1,"timeStamp":"2015-03-20T00:01:44.761","provider":"foo","providerId":null,"lineNumber":1,"summary":"foo","description":"foo: 1"}...
responseType: ""
responseURL: "http//localhost:8080/errors/findAll"
...

Although the data is being received as indicated by the content in responseText field, when console.log(getErrors.responseText) is executed, an empty string is returned. The reason for this discrepancy is unclear.

Javascript snippet:

var getErrors = new XMLHttpRequest();

    getErrors.open('GET', '/errors/findAll', true);
    getErrors.send();

    //var response = getErrors.responseText;

    console.log(getErrors);
    console.log(getErrors.responseText);

Answer №1

Below is my JavaScript code that shows how to handle callbacks:

fetchData = function(url, callbackFunction) // How do I implement this callback?
{
    var request = new XMLHttpRequest();
    request.onreadystatechange = function()
    {
        if (request.readyState == 4 && request.status == 200)
        {
            callback(request.responseText); // Using a callback function
        }
    }
    request.open('GET', url);
    request.send();
}

function callback(response) {
    console.log(response);
}

fetchData('/data/all', callback);

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

Issue with Material-UI tab when using a datatable within it's content

I implemented the Simple Tabs feature from Material-UI with a Tab containing a Datatable using React-Data_Table. However, I noticed that this particular tab is not responsive like the others when the table is full. Empty Full Here's a snippet of th ...

What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions. The first function is handleFileInput: handleFileInput(event){ setTimeOut(async()=>{ let abcd= await this.convertFileToString(this.fi ...

Display the contents in a textarea with modal, not as a string

I'm currently working on implementing a modal overlay window with simplemodal that will display the contents of a text area. My goal is to show the rendered output rather than just the string value. For example, if a user enters HTML or includes an im ...

Struggling to figure out why jqueryrotate isn't functioning as expected

I'm having trouble getting example #2 of jqueryrotate from this page to work on a simple HTML page. Can someone help me figure out what I'm doing wrong? Thanks! Here is the code I'm using: <!DOCTYPE html> <head> <script typ ...

Loading text with a remote web font has been successfully initiated in Fabric.js

Currently, I am immersed in developing a large custom application using Fabric JS and thus far, my progress has been commendable. However, I have encountered an issue concerning the initialization of loaded text objects that utilize web fonts. When the fo ...

Guide on fetching data from a different php file using jQuery's .load() method?

I am trying to use a basic .load() function from jQuery to load a div element with an id from another file in the same directory when changing the selected option in a selector. However, I am having trouble getting it to work. Nothing happens when I change ...

Mysterious line break emerges upon displaying JavaScript through PHP

I have a situation where I am using PHP to output JavaScript for a WordPress shortcode. This is what my PHP code looks like: $output="<script type='text/javascript' > jQuery(document).ready(function() { jQuery('#photo{$photo_id}&a ...

JavaScript: Manipulating Data with Dual Arrays of Objects

//Original Data export const data1 = [ { addKey: '11', address: '12', value: 0 }, { addKey: '11', address: '12', value: 0 }, { addKey: '12', address: '11', value: 0 }, { addKey: &a ...

Tips for retrieving the chosen value from an ajax.net ComboBox using javascript

Is there a way to extract the selected value from an ajax.net combobox using JavaScript for client-side validation? What would be the most effective method to achieve this? Thank you. This is how I managed to obtain the value: var combo = $get('ddl ...

How did the chat sidebar disappear at Facebook when using the "zoom in" feature?

Have you ever noticed that Facebook can detect users' zoom-in level and dynamically add a .hidden_elem classname to hide the .fbChatSidebar? (See attachments below) I've done some research on this feature and came across a GitHub repository call ...

What is the best way to transfer Flow type properties from one React component to another?

I'm in the process of developing a component that will wrap another component known as Button. The tricky part is that the library where Button is defined does not expose the type of its properties. In order to properly assign types to my component, ...

Is there a reason why async functions do not function properly within a controller's get() handler?

Utilizing Node and Express along with the mssql npm package, I establish a connection to an SQL Server database in my app.js file by setting up a global variable that creates a connectionPool (I've excluded some boilerplate code for brevity): const m ...

Tips for ensuring JavaScript promise returns a value before moving forward with execution

In my project, I have created a utility class that acts as a wrapper for a promise-based vendor library. This utility class is used by my application to carry out specific operations. Currently, I am faced with a situation where my code needs to wait for ...

Utilizing Node npm to access the three.js module for front-end development

My current setup involves utilizing node npm for managing dependencies such as jquery on the front end through the method outlined below. Server (successful) app.use('/jquery', express.static(__dirname + '/node_modules/jquery/dist/')) ...

Is there a way to mount or unmount a React component by pressing a single key?

I am currently developing an application that showcases 3D objects upon pressing certain keys on the keyboard. My goal is to have these objects disappear after 2-3 seconds or once the animation completes. Below is the component responsible for managing th ...

Alter based on the RegEx JS value

I have a regular expression that looks like this: /\\.br<[0-9]+>\\/g. I am looking to replace it within the main text with the number of new lines specified between the <> in the regular expression. For example, input: Hel ...

What is the best way to interpret a JSON with nested structure?

I can't seem to find any errors in the code below, but I keep receiving an error message stating "item._highlightResult.map is not a function". {items.map((item, index) => ( <li key={index}><a href={item.story_url} target="_blank& ...

Vibrant DT data table featuring vertical radio buttons

I am in need of a polished DT datatable that includes radio buttons embedded within a column. While this application provides a solution for horizontal buttons, I have taken on the task of adapting it for a vertical layout. Modifying the matrix was a strai ...

Using JQ to structure logs in shell scripting

I've been looking to save some shell scripts into a file for collection by an agent like Fluentbit and sending them off to Cloudwatch and Datadog. I came across this example online that works effectively with the use of jq. __timestamp(){ date &quo ...

Using JavaScript in PHP files to create a box shadow effect while scrolling may not produce the desired result

Issue at hand : My JavaScript is not functioning properly in my .php files CSS not applying while scrolling *CSS Files are named "var.css" #kepala { padding: 10px; top: 0px; left: 0px; right: 0px; position: fixed; background - c ...