The response from the XHR object is coming back as "Object Object

Recently, I've been faced with the challenge of working with an API that provides articles. Within the array returned by the API, there are attributes like author, title, and description. However, despite my efforts, each time I attempt to retrieve this data, all I get back is 'Object Object'.

I have experimented with different methods such as innerHTML, console.log, and now attempting p.textContent. While p.textContent does allow me to access and display some data, it's still not retrieving the specific information I require.

   xhr.onreadystatechange = function() {
      // Only execute if the request is complete
    if(xhr.readyState !== 4) return;
    // Process the returning data
    if(xhr.status >= 200 && xhr.status < 300) {
        // Executed when the request is successful
        var data = JSON.parse(xhr.responseText);

      var body = document.querySelector('.loadNews');
      // Create a paragraph element
      var p = document.createElement('p');
      // Update the content of the p element with API data
      p.textContent = JSON.parse(xhr.responseText);

      // Append the p element to the body
      body.appendChild(p);

The issue persists, resulting in 'Object Object' instead of the desired data from the API response.

Answer №1

When using the JSON.parse method with an object string as input, it will return an object. If you attempt to treat this return value as a string and print it, you will see [object Object]. To access the properties of the object correctly, you should do something like:

data = JSON.parse(xhr.responseText);
p.textContent = 'author: ' + data.author;

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

Using Python to convert a data frame into a nested dictionary

Currently, I have a dataframe structured like this: day account_id balance 2022-11-01 ncw8y7 1.000000 2022-11-02 ncw8y7 1.000424 My goal is to convert it into a nested dictionary format where the first level represents the acco ...

Creating a dropdown menu using Vue.js

My latest project involves coding an html page that features a drop-down list using HTML, CSS, and VueJS. The goal is to have something displayed in the console when a specific option from the drop-down list is selected. Here's the snippet of my html ...

Removing one element from an array with mongoose

As a newcomer to web development, I am currently working on creating a todo app. Below is the schema and model that I have: const tdSchema = new mongoose.Schema({ category: { type: String, required: true, unique: true }, tds: { type: ...

Focusing on a particular iframe

I am currently using the "Music" theme from Organic Theme on my WordPress site and have inserted this code to prevent SoundCloud and MixCloud oEmbeds from stretching the page width: iframe, embed { height: 100%; width: 100%; } Although the fitvid ...

Exploring the power of Angular by implementing nested ng-repeat functionalities:

I am currently working on an ng-repeat feature to add items from the array (album array). Everything seems to be functioning correctly. However, I also have a colors array that should assign different background-colors to the card elements of the album arr ...

What is the best method to invoke a function recursively with a delay of 1 second following the completion of an ajax

I am facing a situation where I need to implement a delay of 1 second after an ajax request is completed, regardless of the outcome. Instead of calling a method every second, I specifically want to call a function 1 second after the ajax request finishes. ...

Simple JavaScript numeric input field

Hey there, I'm a beginner learning JavaScript. I'm currently working on creating a program that adds numbers input through text fields. If you want to check out the HTML code, visit this link on JS Fiddle: http://jsfiddle.net/fCXMt/ My questio ...

Is there a way to customize the selected option in the autocomplete feature of Material UI components?

Is it possible to customize the CSS of selected options in Material UI autocomplete? Can this be achieved by utilizing the theme? ...

Looking for guidance on sending data from a JS file to HTML using Nodejs? Seeking advice on various modules to achieve this task effectively? Let's

Looking for advice on the most effective method to transfer data from a JS file (retrieved from an sqlite db) to an HTML file in order to showcase it in a searchable table. My platform of choice is NodeJS. As a beginner, I am willing to put in extra time a ...

Adjust the color of the Icon within the tab in Material-UI

I'm attempting to change the color of the tab icon that is highlighted while keeping the others unchanged, but I am struggling to find a solution. I am using a MUI component inside the icon button. <Tab icon={ ...

Can a layer be sliced to create a text-shaped cutout?

I want to achieve a cool text effect where the background is visible through the letters. I have explored options with background images and colors, but I haven't found any examples where the underlying layer is revealed. Is this even possible? Imag ...

Unsure how to proceed with resolving lint errors that are causing changes in the code

Updated. I made changes to the code but I am still encountering the following error: Error Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. It is recom ...

What steps can I take to ensure the reset button in JavaScript functions properly?

Look at this code snippet: let animalSound = document.getElementById("animalSound"); Reset button functionality: let resetButton = document.querySelector("#reset"); When the reset button is clicked, my console displays null: resetButton.addEvent ...

Unveiling the mysteries of JSONP in conjunction with AJAX

JSONP allows for bypassing the same origin policy in JavaScript by using <script> tags to load third party data. However, I am uncertain about how JSONP is utilized together with AJAX. My assumption is that: When an AJAX call is initiated, a <sc ...

Add an element to the input field

Two input buttons are available for users to upload files. <input type="file" id="fileUpload" name="files" multiple><br/> <div id="selectedFiles"></div> The selected files will be appende ...

Is the reference to a variable within an array maintained by JavaScript?

I'm working with react code and using the find() method to select an item from an array. When I retrieve an item from the array, is JavaScript copying the item or returning a reference? EDIT: The items in my array are objects, such as [{id: 12, name ...

Restrict the query based on a value within a nested JSON array

Creating a basic table in PostgreSQL 12.3 create table aaa(id integer, data json); The data column is used to store JSON data with the following structure: {     "foo": 1,     "persons": [         {   ...

Loading remote content on a server for my Firefox OS application - On the Web and FxOS device

I haven't come across this issue in any forum, so I decided to reach out here. I'm encountering a problem with my FirefoxOS app on my FirefoxOS device (Geeksphone Developer Preview) when trying to retrieve remote content from the server. I am m ...

Unraveling the Power of Recursive Functions within a React.JS

I'm encountering an issue with a React project. It involves a tic tac toe game where I'm currently working on the implementation of the computer player. The problem arises when the human player clicks on one square (Field-component), triggering ...

differences between using form's get method and sending an angular $http.get request

When trying to make a GET request to a specific URL from my Angular frontend to an ExpressJS backend, I encountered some interesting behavior. In the frontend code snippet below: <li> <a ng-click="givequiz()">GiveQuiz</a> </l ...