Retrieve information dynamically from a JSON file using the get JSON function and iterate through the data

I possess a JSON file that I wish to utilize in creating dynamic HTML elements with the JSON content. Below is the provided JSON data:

{
    "india": [
        {
            "position": "left",
            "imgurl":"3.jpg"
        },

        {
            "position": "right",
            "imgurl":"2.jpg"
        },

        {
            "position": "left",
            "imgurl":"3.jpg"
        },

        {
            "position": "right",
            "imgurl":"2.jpg"
        }
    ],

    "aus": [
        {
            "position": "left",
            "imgurl":"4.jpg"
        },

        {
            "position": "right",
            "imgurl":"2.jpg"
        },

        {
            "position": "left",
            "imgurl":"3.jpg"
        },

        {
            "position": "right",
            "imgurl":"2.jpg"
        }
    ]
}

Displayed below is the snippet of HTML code containing Javascript functionality:

<html>
<head>
  <title>The jQuery Example</title>
  <script type = "text/javascript" 
  src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

  <script type = "text/javascript" language = "javascript">
   $(document).ready(function() {

    $("#driver").click(function(event) {

        $.getJSON('list1.json', function(data) {

            $.each(data.india, function (key, val) {

                $('.ms-left').append('<div class="ms-section '+val.position+'" id="left3"><img src="'+val.imgurl+'"></div>');

            });        
        });
    });
});
</script>
</head>      
<body>
  <p>Click on the button to load result.html file:</p>

  <div id = "stage" style = "background-color:#cc0;">
   STAGE</div>

<ul id="ul"></ul>
<div class="ms-left"></div>

<input type = "button" id = "driver" value = "india" />

<ul id="menu" class="">
    <li><a href="" data-value="india">India</a></li>
    <li><a href="" data-value="aus">Australia</a></li>
    <li><a href="" data-value="usa">USA</a></li>
</ul>       
</body>
</html>

The main challenge I face is passing dynamic variables to each function such as $.each(data.india). Essentially, I aim to change the parameter from India to AUS, USA dynamically so that the .each loop can access and retrieve values based on country parameters defined in the JSON data. Assistance is requested for this task.

How can I implement passing a dynamic parameter to the .each loop in order to efficiently fetch data according to the countries specified in the JSON file? As it stands, the data.india, data.aus references can be manually modified to obtain desired information, but I seek a method to automate this process dynamically.

Above my code lies a structure consisting of list items. My objective entails clicking the link corresponding to India, which will then request JSON data associated with India. Similarly, clicking the AUS link should retrieve relevant data from the JSON source pertaining to Australia.

Answer №1

@creativecoder Some suggestions for you:

  • Place JavaScript code at the bottom of the <body> tag, not within the <head>.
  • Maintain consistent indentation using either tabs or spaces, with a preference for spaces due to their universality.

Now, here is the resolution to your issue:

<html>
<head>
    <title>The jQuery Example</title>
</head>
<body>
    <div id="stage" style="background-color:#cc0;">STAGE</div>
    <div class="ms-left"></div>
    <ul id="menu" class="countries">
        <li><a href="#" data-value="india">India</a></li>
        <li><a href="#" data-value="aus">Australia</a></li>
        <li><a href="#" data-value="usa">USA</a></li>
    </ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>
        var json = {
            "india": [
                {
                    "position": "left",
                    "imgurl": "3.jpg"
                },
                {
                    "position": "right",
                    "imgurl": "2.jpg"
                },
                {
                    "position": "left",
                    "imgurl": "3.jpg"
                },
                {
                    "position": "right",
                    "imgurl": "2.jpg"
                }
            ],
            "aus": [
                {
                    "position": "left",
                    "imgurl": "4.jpg"
                },
                {
                    "position": "right",
                    "imgurl": "2.jpg"
                },
                {
                    "position": "left",
                    "imgurl": "3.jpg"
                },
                {
                    "position": "right",
                    "imgurl": "2.jpg"
                }
            ]
        };
    </script>
    <script>
        var populate = function (country) {
            $('.ms-left').empty();
            $.each(json[country], function (key, value) {
                var _div = $('<div>')
                    .addClass('ms-section')
                    .addClass(value.position)
                    .append($('<img>').attr('src', value.imgurl));

                $('.ms-left').append(_div);
            });
        };

        $(document).ready(function() {

            /**
             * Obtain your JSON data and store it locally,
             * loading the file each time is not recommended
             * if the file remains unchanged.
             */

            $('.countries a').each(function() {
                $(this).on('click', populate.bind(this, $(this).data('value')));
            });
        });
    </script>
</body>
</html>

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

Can the AJAX URL be loaded onto a new page?

https://i.stack.imgur.com/5l63v.pngPardon the poorly phrased question, but I need some guidance on a specific requirement regarding opening a URL in a new page. Currently, I have designed an AJAX URL and I'm wondering if it's possible to open thi ...

How to integrate a jQuery plug-in into your Meteor 1.7.0.3 project

Recently, I delved into using Meteor for the first time, and it has been about a week since I started exploring its functionalities. However, I encountered an issue with integrating jQuery plugins that were installed via npm. After running: meteor npm i ...

Display different images based on user selection in vue.js

I am new to working with vue.js and I'm facing a challenge. My goal is to display images of NBA players based on the selected criteria using vue.js. For instance, if the Dunk contest champion is chosen, only images of Kobe and Jordan should be display ...

Import JSON Document for Parsing

Currently, I am implementing a customized version of Bootstrap. You can find it at this link: . In my application, there is a button for uploading a file that contains JSON data. My goal is to be able to read this file in my Controller. Can anyone sugges ...

Having issues with your JQuery code?

I am attempting to locate a cell within a table that contains the class 'empty'. My goal is to then utilize a code snippet to obtain the id (cell number) and determine which cells are adjacent to it. As part of my test, I am experimenting with t ...

ng-options is not compatible with an object as a source

It seems like there should be a simple solution to this issue, but I'm struggling to get ng-options to work with my model object. Essentially, I want to populate my select dropdown with a list of countries. Each option value should be a country code a ...

What is a dynamic component in Vue with Typescript?

I need help implementing type checking for my dynamic component instead of relying on 'any' as a workaround. Can someone guide me through the proper way to achieve this? <script> ... interface { [key: string]: any } const pages: page = ...

I encountered a CORS policy error while using React. What steps can I take to effectively manage and resolve this

INDEX.JS import express from "express"; import { APP_PORT } from "./config"; import db from "./database"; import cors from "cors"; import bodyParser from "body-parser"; import Routes from "./routes&quo ...

results vary when using both a while loop and callback

I'm having an issue with my while loop when filtering data from mongodb. Even though I should be getting three entries logged to the console, only one entry is making it to the callback function. Can anyone explain why this is happening? while(i--) { ...

Tips for passing the id using jQuery in an AJAX request to execute a delete action

How can I remove an element from a list by clicking the delete button? https://i.sstatic.net/dQuOu.png I have created an ajax call for this purpose: .ajax({ type : "GET", url : 'getVenueList&apo ...

Converting JSON data in Spring MVC 3.2 for REST services

I am encountering an issue while attempting to send a List of data as JSON from my Spring Controller. The error message "Could not find acceptable representation" is being thrown. Below are the snippets of code from different parts of my application: pom. ...

Retrieve a single document using Angularfire2 without setting up a listener

I'm facing an issue with angularfire2 v6 and angular 11. Specifically, I am attempting to retrieve a single document from the users collection based on their email without utilizing valueChanges() or snapshotChanges(). Realtime updates are not necessa ...

Please refrain from clearing the text field as it will delete the input value

I feel like I must be overlooking something really minor because I just can't seem to find it! I've been attempting to sanitize the text input by setting the state to ('') and while it clears the variable, the HTML input keeps displayi ...

MongoJS Node findOne query inaccurately returns empty result set

Utilizing MongoJS: https://github.com/mafintosh/mongojs Retrieves all data Returns an empty array</p> The database contains the data I am looking for. I've also tried searching using a different key (such as name). Why is it unable to locate ...

Tips for segmenting text into pages according to the dimensions of the viewport and the font style

Here's a puzzle for you. I have a horizontal slider that loads pages via Ajax, with pre-loading features to maintain smooth performance. Similar to Facebook Billboarding but with a slight twist. By determining the viewport size, I calculate boxSizeX a ...

Develop an engaging billboard carousel using jQuery

After coming across a tutorial on tympanus, I decided to make some modifications to create a rotating billboard effect. However, something seems to be going wrong and it's driving me crazy trying to figure out the problem! $(function() { $('#ad_ ...

Vue component fails to react to updates from Vuex

Currently, I am developing a system to facilitate the management of orders at a shipping station. Although I have successfully implemented the initial changes and most of the functionality, I am encountering an issue where one component fails to update ano ...

Discovering the total number of tickets based on priority in an array with Javascript

I have the following data set { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"Medium", task_id:T1 } { agent_id:002, priority:"High", task_id:T1 ...

Having Issues with JSFiddle: Difficulty with executing a basic onclick event to display a string

Having trouble with an onclick event: Simply click the button to run a function that displays "Hello World" in a paragraph element with id="demo". <button onclick="myFunction()">Click me</button> <p id="demo"></p> <script> ...

Having trouble fetching information from a JSON file stored in a local directory while using Angular 7

I am currently experiencing an issue with my code. It works fine when fetching data from a URL, but when I try to read from a local JSON file located in the assets folder, it returns an error. searchData() { const url: any = 'https://jsonplaceholde ...