Using AJAX to retrieve a specific JSON object from an array of JSON data

Data retrieved in JSON array from the API:

[{"id":"001", "name":"john", "age":"40"}, {"id":"002", "name":"jane", "age":"30"}]

Using Ajax:

  $.ajax({                                      
  url: 'interface_API.php',                                                              
  dataType: 'json',                    
  success: function(data)         
  {
    for(var i in data){
        var row = data[i];

        var id = row.id;            
        var name = row.name;
        var age = row.age;

    $('#output').append("<tr width='50%'><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td></tr>");
    }
  } 
});

The PHP code uses this logic to create the JSON object:

if(mysqli_num_rows($output)){
     while($row = mysqli_fetch_assoc($output)){
         $json[] = $row;
     }
}

However, I am getting 'undefined' repeatedly for each .append operation.

What is the correct way to extract each JSON object from the array and append it to the page?

Answer №1

modify this:

let id = row[0];            
let name = row[1];
let age = row[2];

to any of these options:

let id = row['id'];            
let name = row['name'];
let age = row['age'];
let id = row.id;
let name = row.name;
let age = row.age;

You had already accessed the data in this loop:

for(let i in data){
    let row = data[i]; // <----this line

Therefore, you only need to refer to it using object keys.

Answer №2

To improve the for loop, consider implementing it in the following way:

$.ajax({                                      
  url: 'api_interface.php',                                                              
  dataType: 'json',                    
  success: function(response)         
  {
    for(let index in response){
        let row = response[index];

        let id = row.id;            
        let name = row.name;
        let age = row.age;

$('#results').append("<tr width='50%'><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td></tr>"); 
}
} 
});

Answer №3

Remember to utilize the key when extracting the JSON Object

let items=[
        {"id":"5","text":"example1"},
        {"id":"6","text":"example2"},
        {"id":"7","text":"example3"},
        {"id":"8","text":"example4"}

         ]


    console.log(items[1].text)

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

The PHP regular expression syntax can be used to capture all occurrences of a specific format

I have a string where I need to extract specific format instances: My new Apple [PT# 789790XYZ; Apple] is great but my colleague has the latest Samsung [PT# GH-5678ujk; Samsung] that's even better. The desired extractions are: [PT# 789790XYZ; App ...

Is there a way to implement absolute imports in both Storybook and Next.js?

Within my .storybook/main.js file, I've included the following webpack configuration: webpackFinal: async (config) => { config.resolve.modules = [ ...(config.resolve.modules || []), path.resolve(__dirname), ]; return ...

Displaying Real-Time Values in ReactJS

Hi there, I am currently using the code below to upload images to Cloudinary: import React, { Component } from 'react'; import './App.css'; import Dropzone from 'react-dropzone'; import axios from 'axios'; const F ...

Using JavaScript to create a dynamic to-do list that persists on the browser even when refreshed

I created a Javascript Todolist that is functioning well, but I am seeking a way to ensure that my Todo-items persist on the browser even after refreshing until I choose to delete them. Any suggestions or advice on how I can achieve this? ...

How can I utilize a filter or pipe to populate product categories onto screens within Ionic 2?

I am considering creating an Ionic 2 app with 6 pages, but I'm unsure whether to utilize a Pipe or a Filter for the individual category pages and how to implement the necessary code. Each category page should be able to display products from the "app ...

pythonWhy is textwrap giving unexpected results when formatting in JSON?

>>> a = '{"key1": "aaaaaaaaaaaaaaaaa", "key2": "bbbbbbbbbbbbbbbbbbbbbbbb"}' >>> len(a) 64 >>> textwrap.wrap(a, 32, drop_whitespace=False) ['{"key1": "aaaaaaaaaaaaaaaaa", ', '"key2": ', '"bbbbbbb ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

Having issues displaying the & symbol in HTML from backend data

I recently worked on a project using express handlebars, where I was fetching data from the YouTube API. However, the titles of the data contained special characters such as '# (the ' symbol) and & (the & symbol). When attempting to render the ...

What changes can be made to index.php in order to access my website through a specific directory?

After restoring my website from a backup, I need help getting my index.php to work properly. Issue: Prior to the crash, all folders and files were located under the /se427 directory. This setup made future upgrades easier from socialengine.com. Social E ...

Building an array of ids that contain the checkbox type using jQuery: What's the best way?

Below is the HTML snippet I am working with: <!-- Parent checkbox code goes here --> <input id="ckbCheckAll" class="custom-check ez-hide" type="checkbox" name=""></input> <!-- Child checkbox codes follow --> <input id="practice_ ...

Mobile Windows Z-Index

Struggling with the z-index issue on a video tag in Windows Mobile, particularly when it comes to my search box. <div portal:substituteby='common/search::search'></div> The goal is for the search box to appear above the video. ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

The process of JavaScript for detecting and extracting text from

After much searching, I stumbled upon this intriguing piece of JavaScript code at this location. Curiously, I was able to remove a few eggs using the following script: var eggCoordinates = []; for (var i = 0; i < 5; i++) { eggCoordinates.push(new E ...

I need help figuring out the right way to define the scope for ng-model within a directive

I found a straightforward directive to automate sliders: app.directive('slider', function() { return { restrict: 'AE', link: function(scope, element, attrs) { element.slider({ value: scop ...

``Please proceed with the form submission only if it has been verified and

Within my web application, there are several pages that handle submitted data from forms. I would like to prevent the following scenario: A user creates a form on the client side with identical fields to my original form and sends it to the URL responsibl ...

Changing the label of a ChoiceType in Symfony2

Within a form, I have a select field (choiceType) that automatically populates with all the lines from another table. I am trying to modify just the label of the select field without changing its content... For textType fields, I was able to achieve this ...

Rest parameter ...args is not supported by Heroku platform

When interacting with Heroku, an error message SyntaxError: Unexpected token ... appears. What modifications should be made to this function for compatibility with Heroku? authenticate(...args) { var authRequest = {}; authRequest[ ...

Folding without extending

My button has a div inside it with content. I've set it up so that when the div is clicked, the collapsed content expands. The hover effect changes color and pointer as expected. But for some reason, clicking on the div doesn't expand the content ...

Safari's Failure to Execute Ajax Requests

My HTML page includes an ajax request that is functioning properly on Firefox, but does not work on Safari. While debugging, I noticed that the readystate is undefined and the status is "". Can anyone suggest why it might not be working on Safari? Javascr ...