Displaying Array Information in JavaScript

After spending a significant amount of time searching online, I have not been able to find a working solution to achieve what I need.

Essentially, I am making an AJAX request that executes a database query and then outputs the results using echo json_encode($row);

Once this JSON data is returned to my JavaScript, I am facing some challenges. I need to parse the JSON array and extract specific elements to dynamically update input field values. Below is the code snippet I am using to make the AJAX request and receive the JSON array:

var vars = new XMLHttpRequest();
    vars.onload = function() {
        var retrieved = new Array(this.responseText);
        document.getElementById("testingOutput").innerHTML = retrieved;
};

vars.open("GET", "https://my.url.here", true);
vars.send();

I have attempted a few methods to extract data from the array without success (I am relatively new to JavaScript). For example, I tried accessing the data using keys like retrieved['first_name'] and indexes like retrieved[1], but none of these worked. I also experimented with 'for' loops, but couldn't get them to function as expected.

Ultimately, I simply need a way to extract specific data from the array to use in jQuery as shown below:

$("#firstname").val = forename;
$("#lastname").val = surname;

Any assistance would be greatly appreciated as I am feeling quite frustrated at this point!

EDIT: Initially, I tried setting

var retrieved = (this.responseText);
, which resulted in the data being detected as a string when checked with typeof. On the other hand,
var retrieved = new Array(this.responseText)
indicated that the type was an object. I am unsure of how to access the data in either case.

Answer №1

When sending JSON data, make sure to parse it in your JavaScript code to convert it into a native object

var retrieved = JSON.parse(this.responseText);

For more information on JSON.parse click here


Following advice given by kiltek, using console.log or console.dir for debugging will help you visualize the data structure you are dealing with

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

Including jQuery in an Angular project generated with JHipster

I am facing a challenge with integrating jQuery into my Jhipster Angular project as a newcomer to Jhipster and Angular. My goal is to customize the theme and appearance of the default Jhipster application, so I obtained a theme that uses a combination of ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...

What is the comparison between actual pixels and text size in Internet Explorer?

Can you determine the actual font size in pixels corresponding to the following text size options in Internet Explorer? Largest Larger Medium Smaller Smallest In a web development project, I am looking to achieve a similar functionality to adjust the te ...

Rotate the image as you swipe left or right with Angular's ng-swipe-left and ng-swipe-right features

I am currently utilizing angular's ng-swipe-left and ng-swipe-right to detect swipe events on touch devices. My goal is to rotate an image based on the speed and direction of the swipe while it is still in progress. However, I am facing a challenge as ...

A guide to implementing infinite scrolling with vue-infinite-loading in Nuxt.js (Vue.js)

Currently, I am working on developing a web application using Nuxt.js (Vue.js). Initially, to set up the project, I used the command: vue init nuxt/express MyProject ~page/help.vue <template> <div> <p v-for="item in list"> ...

Utilizing TypeScript generics to accurately extract type information from state during reduction

In the context of a state reducer presented as follows: const anObject = { fruit: 'Apple', today: new Date(), } function reducer(state, stateReducer) { return stateReducer(state); } const fruit = reducer(anObject, state => state.fruit ...

Transform the structure of an object using Ramda from its original form

Is it possible to transform an object by modifying and filtering it to create a different shape that is easier to work with after making an API request? I've been struggling to find elegant solutions that don't involve using path and prop for eve ...

Issue with setting state in useEffect causing an infinite loop due to either linter warning or user error

In its current state, my component appears as follows: const { listOfStuff = [{name:"john"},{name:"smith"}] } = props const [peopleNames, setPeopleNames] = useState([]) useEffect(() => { listOfStuff.forEach(userName => { setPeopleNames(people ...

Are the charts missing from the Django admin interface?

I am working on incorporating charts into my admin view by extending the admin/base.html file. Instead of using libraries like charts.js, I prefer to use a template for displaying the charts. Ideally, I want my view to resemble this example (). You can fin ...

developed a regular expression to disregard .goutputstream documents

After successfully creating a watcher with chokidar, I encountered an issue when trying to ignore certain files using regex. I am struggling to figure out what went wrong in my code or regex implementation. Below is the snippet of the code: const watcher ...

Is there a way to automatically redirect the server URL when a file is modified?

I am currently experimenting with a function that is supposed to only display a message in the console without redirecting the actual URL of my server when a file is changed. watcher.add("/home/diegonode/Desktop/ExpressCart-master/routes/2.mk"); watche ...

Is the vertex count of a Geometry in Three.js increased when it is converted to a BufferGeometry?

Recently, I've been experimenting with the fromGeometry method to convert regular Geometry objects into BufferGeometry objects. To my surprise, I noticed that the number of vertices increases during this conversion process. For instance, consider the ...

Issues arise when handling characters with accents in Android JSON with PHP due to improper handling

Essentially, I am facing issues with French characters when sending a string from my Android app to PHP and decoding it using JSON. Here is the process in detail: HttpPost httppost = new HttpPost(//my server and filename); try { List<Na ...

Bitwise exclusive OR with an unsigned character

I am encountering an unexpected issue while attempting to execute an XOR operation between a 64-bit key and a 64-bit unsigned char array. The output seems quite unusual. Could this be due to a problem with the data type or the sequence of operations? #incl ...

Creating a script that automatically launches the terminal and executes specific commands

Can anyone help me with creating a file that, when clicked on, opens a command prompt and executes the following commands? cd desktop\discordBOT node . Many thanks in advance! ...

What is the reason for substituting a reference to an object with its actual value?

I am utilizing node.js and express. Within the 'req.session', I have stored a complex object containing an array of objects. Additionally, I store a reference to one of the objects in the array. For example: var value = { name: "name" , ...

Choose the DIV element based on its data attribute using JSON

When using each(), my goal is to: Hide all divs where the data-infos.grpid = $jQuery(this).data('infos').grpid Show the next div where data-infos.ordre = $jQuery(this).data('infos').next_ordre I am unsure how to apply a "where" ...

Transforming CSV data into a particular JSON structure using PHP

I currently have a PHP script that converts CSV data to JSON format, but I am looking to modify the structure of the output JSON. Here is an example of my CSV data: Icon Name, Responses, Performance 03_v10_Assembly_point, 225, 38 55_v10_Fire, 203, 87 ...

Tips on efficiently reusing a variable

As someone who is relatively new to Jquery and Javascript, I have been attempting to search for a solution to my question on this platform. However, it seems that the terminology I am using may not be accurate enough to yield relevant results. If there is ...

What is the strategy to load a div exclusively when triggered by a click event, instead of loading it

Can anyone assist me with a problem I am facing on my scripting page? I am currently working on a website that showcases properties. I would like to know how to prevent a specific div from loading when the page initially loads, and instead have its content ...