Showing various JSON arrays using AJAX and JavaScript

I've encountered a challenge with showcasing multiple JSON arrays and would greatly appreciate any assistance on this matter.

JSON

{ 
"houseOne": [
    {
        "name": "John Clarke",
        "age": 22,
        "dob": "19-11-90" 
    },
      {
        "name": "Mitch Woodier",
        "age": 20,
        "dob": "23-10-92"  
    },
      {
        "name": "Mavis Waddingham",
        "age": 21,
        "dob": "10-11-91"  
    }
],

          "houseTwo": [
    {
        "name": "Luke Woodier",
        "age": 22,
        "dob": "19-11-90" 
    },
      {
        "name": "Rob Clarke",
        "age": 20,
        "dob": "23-10-92"  
    },
      {
        "name": "Alex Gayfag",
        "age": 21,
        "dob": "10-11-91"  
    }
]

}

Javascript

<script type="text/javascript>
    function ajaxRequest(url)
    {
       var request = new XMLHttpRequest();

            // Addressing IE caching issue
            if (url.indexOf('?') < 0) {
                today = new Date();
                url += '?' + today.getTime();
            }

        request.open("GET", url, false);
        request.setRequestHeader("Cache-Control", "no-cache");
        request.send();
        return request.responseText;
    }

    var data = ajaxRequest("results.json");
    var houses = JSON.parse(data);

    function displayJson() {
        var myDiv =document.getElementById("content");
        for (house = 0; house < 3; house++) {
            var home = houses.houseOne[house];
            myDiv.innerHTML += houseDetails(home,house);

         }
    } 


    function houseDetails(home,houseNumber){


    var myHTML = "<h1>House Mate "+ (houseNumber +1)+"</h1>";
    myHTML += "<table>";
    myHTML += "<tr><th>Name</th><th>Age</th><th>D.O.B</th></tr>";
    myHTML += "<tr>";
    myHTML += "<td>";
    myHTML += home.name;
    myHTML += "</td>";
    myHTML += "<td>";
    myHTML += home.age;
    myHTML += "</td>";
    myHTML += "<td>";
    myHTML += home.dob;
    myHTML += "</td>";
    myHTML += "</table>";

    return myHTML



    }      

</script>

Though I managed to display houseOne as a table, I'm struggling to showcase both houseOne and houseTwo. I hope this clarifies the situation as I'm still learning about web development.

Best,

Dean

Answer №1

Within your displayJson() function, you are solely making reference to house.houseOne

var residence = houses.houseOne[house];

Below is an enhanced version (which includes jQuery as well) http://jsfiddle.net/XzZUR/1/

JSON

var houses = {
    "houseOne": [{
        "name": "John Clarke",
            "age": 22,
            "dob": "19-11-90"
    }, {
        "name": "Mitch Woodier",
            "age": 20,
            "dob": "23-10-92"
    }, {
        "name": "Mavis Waddingham",
            "age": 21,
            "dob": "10-11-91"
    }],

        "houseTwo": [{
        "name": "Luke Woodier",
            "age": 22,
            "dob": "19-11-90"
    }, {
        "name": "Rob Clarke",
            "age": 20,
            "dob": "23-10-92"
    }, {
        "name": "Alex Gayfag",
            "age": 21,
            "dob": "10-11-91"
    }]
};

Javascript

function displayJson() {
    var myDiv = $("#content");

    $.each(houses, function(){
        var house = this;
        $(house).each(function(key){
            myDiv.append(houseDetails(this,key));
        })
    });

}

Answer №2

It is advisable to avoid using synchronous ajax requests and opt for a callback function instead. To iterate through each house object, you can follow this approach:

function displayJson() {
    var i,h,ret=[];
    var myDiv =document.getElementById("content");
    // houseone and housetwo
    for (h in houses) {
        // houseone and housetwo are arrays: [house,house,house]
        // for every house in this array do:
        for(i=0;i<houses[h].length;i++){
          var home = houses[h][i];
          ret.push(houseDetails(home,i));
        }
     }
     //setting innerHTML can be resource intensive
     // it's better to avoid doing this within a loop.
     myDiv.innerHTML=ret.join("");
} 

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

Assigning binary messages a structure similar to JSON for the purpose of easy identification

Is there a way to differentiate binary messages from a server by tagging them with a type attribute? Currently, I am working with node.js and sending binary images as blobs to my client. However, I now also need to send other file types like .txt over the ...

JSLint error: Inconsistent use of spaces and tabs detected

I recently ran the code below through JSLint: $(document).ready(function() { /* Insert paragraph upon page load */ // Retrieve all header elements var header = document.getElementsByTagName('h1'), parent, ...

The resizing function on the droppable element is malfunctioning on Mozilla browsers

I've been working on making one div both droppable and resizable. Surprisingly, everything is functioning perfectly in Chrome but not in Firefox. If you'd like to see the issue for yourself, here is my jsFiddle demo that you can open in Firefox: ...

Tips on altering button color when input field is populated

I have been researching online and have not come across any discussions on how to dynamically change the color of a button in JavaScript when an input field is filled. I haven't really tried any code myself because there are very limited resources add ...

Effective strategies for managing form submissions with React and Typescript

As I dive into refactoring my code to TypeScript, especially as I am still getting accustomed to it, I find myself pondering about the HTML element types with React events. This has led me to rethink how I approach form creation and submission event handli ...

What's the best way to retrieve a value from a function that invokes itself multiple times?

My task involves navigating through nested object data to find a specific result. I am using the findByKey function, which recursively calls itself until the desired result is found. However, instead of returning object.source, I am getting undefined. as ...

The Spring Boot and Angular Fusion Application

Currently, I am in the process of developing a Spring Boot Application with Angular as the frontend and Spring-Boot for the backend. My goal is to create a deployable war. After researching various resources online, my current understanding is that Spring ...

Determining the selection status of an HTML input

I have been working on a unique calculator that calculates the Body Mass Index of individuals. It performs well when I manually input the values, utilizing jQuery to execute the calculations. However, my goal is to enable users to enter values using numbe ...

Implement dynamic routing in Express by utilizing handlebars templates

My current goal is to extract a page name from a GET request using express so that I can dynamically load a handlebar file based on this specified name. The challenge arises when the page loads, as express continues to receive requests for assets such as ...

Using jQuery to select a div element that has been dynamically loaded using ajax, or inserted into the DOM using the html()

Greetings from a newcomer to stackoverflow! After searching for similar questions and answers, I still couldn't find a solution to my specific problem. Here's the situation: I have a webpage that uses ajax to load main content. The function for ...

Information is inaccessible beyond onBeforeMount in the Composition API of Vue 3

In my code snippet block, I have the following code: <script setup lang="ts"> import ApiService from '../service/api' import { reactive, onBeforeMount } from 'vue' let pokemons = reactive([]) onBeforeMount(async ()=> ...

Using Play Framework to override the apply method in a JSON Read combinator

I'm attempting to create something similar to the following: case class Data(name: String, dataList: List[Integer], isPossible: Boolean) { override def apply(name: String, list: List[Integer]): Data = { Data(name, list, list.exists((x: Inte ...

Struts2 iterator failing to print any output while traversing through JSON string

My Struts 2 application is set up to display data by iterating through a JSON object stored in the Struts2 session using the Struts2 iterator as shown below: <s:iterator var="menu" value="userMenu.get('permissions')"> <s:property val ...

Determine the mean value of an element within a specific column of arrays containing JSON data stored in a PostgreSQL database

Within my postgres table, I have a column that stores JSON data in the form of an array represented as a string. Here is an example: [ {"UsageInfo"=>"P-1008366", "Role"=>"Abstract", "RetailPrice"=>2, "EffectivePrice"=>0}, {"Role"=>"Text ...

Enhanced page flow with CSS and jQuery

I'm looking to improve the overall layout of my webpage, but I can't seem to pinpoint exactly what it is that I need! Imagine you have the following HTML structure: <section> <article> <h1>Article Header</h1> & ...

How can you condense specific array elements into a single array, while grouping the remaining elements under a separate category?

I have an array with common names and different surnames. I want to consolidate all these names into one array and keep the surname arrays nested inside. Here is an example: Array ( [0] => Array ( [Name] => Rahul ...

Displaying items from an array is made easy thanks to the combination of mapGetters, VUEJS, vuex, and vuetify

My website has two main routes: one for the home page and another for a configuration panel. In the home page, there is a container displaying information such as date, time, current temperature, etc. Below that, there is another container where users can ...

Flexbox helps create responsive layouts with ease

Utilizing flex to centrally position my element within my layers has worked well for me, but I encountered an issue when switching to a smaller screen size. The element simply scales down in size instead of taking up the full width like it does with Bootst ...

What could be causing my jQuery to suddenly stop functioning?

My website has a simple jQuery function that expands information divs. It was working perfectly fine until the other day when I made some changes to my site (not related to the jQuery) and now it's suddenly not working at all, and I can't figure ...

Variety of hues present on the mesh surface facing the plane

I am facing a challenge in coloring a face that is looking towards a plane. I have considered two different approaches: One option is to position a light source below the plane (which is only one-sided) so that the underside of the object receives a l ...