Utilizing JavaScript to iterate through objects retrieved via Ajax calls

Recently, I've been diving into the world of Javascript and delving deep into AJAX. Utilizing Vanilla JS along with simple AJAX, my current task involves fetching a user object from a URL based on the user's input ID. Despite attempting to use .data, I am encountering issues getting it to function properly.

async function display() {
  try {
    let id = +userID.value;
    const url = `https://jsonplaceholder.typicode.com/users/${id}`;
    const response = await fetch(url);
    const rootObject = await response.json();
    const users = rootObject.data;
    getUser(users);
  } catch (err) {
    alert(err.message);
  }
}

display()

Within my code lies another function - getUsers(users), which remains empty due to its malfunctioning state. How can I successfully retrieve the desired object solely from the provided URL?

Answer №1

The JSON response does not contain a data property. To access the data, simply parse the JSON and pass it as an argument to the getUser function.

function getUser(data) {
  for (const prop in data) {
    console.log(`${prop}: ${data[prop]}`);
  }
}

async function display(id) {
  try {
    const url = `https://jsonplaceholder.typicode.com/users/${id}`;
    const response = await fetch(url);
    const data = await response.json();
    getUser(data);
  } catch (err) {
    console.error(err.message);
  }
}

display(3);

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

Extract data from JSON in Google Sheets

UPDATE: entry.content.$t is actually not the correct field to access individual cells. The proper method is using entry.gsx$[cell column header]. Thank you for pointing out this mistake and assisting in finding a solution. Initial inquiry: I am currently ...

Getting the Request Body Content in Express Middleware

Currently, I am in the process of developing a small API logger to use as an Express middleware. This logger is designed to gather data from both the request and response objects, then store this information in a JSON file on disk for later reference. Her ...

Transferring an Array from PHP to Javascript

I'm attempting to pass a PHP array so that I can use it in JavaScript. The PHP code I have written is shown below: <?php $link = mysqli_connect("localhost", "root", "password", "database"); /* check connection */ if (mysqli_connect_errn ...

A guide on displaying information in a dropdown menu using JQuery, Ajax, and Backbone.Marionette

Currently, I am utilizing backbone and marionette for a web application. My objective is to populate a drop-down menu with JSON data once an option has been selected. The process involves the user selecting their account type, triggering an AJAX request, ...

Unable to adjust layout when code is functioning alongside background-color

I'm looking to dynamically change the position of an item on my webpage when it is clicked. Is there a way I can achieve this without relying on id names? I currently have a code snippet that successfully changes the background color, but for some rea ...

Tips on making the form validation script operational

After developing a form alongside a form validation script to ensure that all fields are completed, the name and city sections only contain letters, while the age and phone sections solely include numbers, issues have arisen. It seems that despite the cons ...

Tips for parsing CSV files using d3 version 4

I'm currently grappling with the documentation for CSV Parse in D3. My code snippet looks like this: d3.parse("data.csv",function(data){ salesData = data; }); Unfortunately, I keep encountering this error: Uncaught TypeError: d3.parse is n ...

Is there a way to create an infinite fade in/out effect for this?

Is there a way to ensure that the method runs after the "click" event in this code snippet? The code currently fades in and out the div #shape while the start variable is true, but when I call the "start" method from the "click" event, the browser stops wo ...

Tips for refreshing only a portion of a webpage using JavaScript/jQuery

I have two distinct navigational sections on my website. The left column has its own navigation menu, while the right column (main content area) contains a separate set of links: My goal is to click on a link in the left-hand sidebar (such as "Resume", "E ...

Laravel is failing to send a response when trying to pass a PHP variable using Ajax

When I send an AJAX request to the controller, I am receiving a success alert message. View $(".SendEvents").click(function(e){ e.preventDefault(); var ids = $(this).attr("id"); $.ajax({ type:&a ...

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

Updating the default value of a MUI TextField: Step-by-step guide

I am in the final stages of completing my form, but I have encountered an issue when trying to display the current user's name in the defaultValue variable of the TextField from MUI. If the value starts as ""/null, or essentially empty, the ...

Creating a bold portion of a string

My task involves dynamically creating <p> elements within a div based on the contents of my codeArray, which can vary in size each time. Instead of hard-coding these elements, I have devised the following method: for(i=1;i<codeArray.length;i++) ...

Clarity on confusion between Ajax server-side and client-side execution is required

Imagine a scenario where an autocomplete widget fetches data from a database. Suppose we need to: Get the content from DB1 displayed when the user clicks on the input field. After the user makes a selection, we must: Query DB1 for more data related ...

The Javascript Date constructor struggles to interpret date strings in certain timezones that are not enclosed in brackets

Take a look at the examples below: new Date("Wed, 28 May 2014 09:50:06 EEST"); // Invalid Date new Date("Thu, 26 Jun 2014 09:09:27 EDT"); // OK, is parsed new Date("Wed, 28 May 2014 09:50:06 (EEST)"); // OK, is parsed new Date("Thu, 26 Jun 2014 09:09:27 ( ...

Utilizing AngularJS filter in JavaScript without AngularJS Framework

This is a test to experiment and learn. Currently, I have a JSON object called obj. My goal is to utilize the angular Json filter to format this JSON object and display it in the chrome console. This should be achieved without the need for any button click ...

Angular 2 partial static routing parameters with customizable features

Can an angular 2 routing configuration include a partial-static parameter? Currently, I am using a classic parameter setup like this: const routes: Routes = [ { path: ':type/fine.html', pathMatch: 'full', redirectTo: &ap ...

Tips on positioning content beneath a fixed header or navigation bar when viewed in a web browser

Hi, I'm having an issue with creating a fixed header using HTML and CSS. When I set my header to be in a fixed position, it covers up the content below it. I want the content to be positioned under the header when the page is loaded. Additionally, I&a ...

Issue encountered while trying to define a global variable within a JavaScript Class

I'm currently working on setting up a page variable that can be utilized by my Scroller class for implementing infinite scrolling. It's crucial for this variable to have global scope, as it needs to retain its value outside of the ajax function. ...

Every single checked value in the checkbox variable

Encountered a small hiccup. Let me explain. In my form, there are 8 checkboxes. The goal is to loop through and capture the value of each checked checkbox using a variable. However, I'm always getting the same value from the first checkbox. Here&apo ...