Retrieve data from an online JSON file

I am still learning about working with json and would appreciate some guidance. The data file I need to access is located at this url -
I would like to display it in the following format:

<ul id="smenu">
    <li></li>
</ul>

Could someone please help me understand how to request the data from the given url, iterate through it using a loop, and print it out? I attempted the provided code but it did not work as expected. Thank you for your assistance :)

var xmlhttp = new XMLHttpRequest();
var url = "http://www.thedailystar.net/json/category";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
        myFunction(myArr);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var out = "";
    var i;
    for (i = 0; i < arr.length; i++) {
        out += '<li href="' + arr[i].name + '">' +
            arr[i].display + '</li><br>';
    }
    document.getElementById("smenu").innerHTML = out;
}

Answer №1

If your JavaScript is running on a different domain than thedailystar.net, it will trigger a cross-domain request. In such cases, you must enable CORS on your server that hosts the resource ().

Typically, enabling CORS requires the server to include the following header in its response:

Access-Control-Allow-Origin: *

For more details on CORS, visit: http://enable-cors.org/server.html

Answer №2

The information in the link you shared includes an element labeled category which consists of an array. It seems like this is the specific data you are looking to process. In order to achieve this, simply update the function call from:

myFunction(myArr);

to:

myFunction(myArr.category);

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 data type 'StaticImageData' cannot be converted to type 'string'

I've hit a roadblock with interfaces while working on my NextJS and TypeScript project. I thought I had everything figured out, but I'm encountering an issue with the src prop in my Header component. The error messages I keep receiving are: Typ ...

AngularJS: Modify Z-Index on Click Event

My current project involves a navigation bar with four items, each accompanied by an icon. These icons are positioned absolutely one behind the other and are loaded into the view from different templates within the same controller. I am attempting to dyna ...

Button click not triggering Ajax functionality

I've been working on implementing a simple Ajax function in a JSP using JQueryUI. The goal is to pass two text fields from a form and use them to populate two separate divs. However, when I click the button, nothing seems to be happening. I even tried ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

In JavaScript, provide a boolean response to a callback function from a separate function

Working with the jQuery validate plugin involves utilizing a submitHandler callback function. This function determines whether the form submission should proceed based on its return value - false will prevent submission, while true will allow it to go thro ...

Encountering npm install failure post updating node version

When attempting to execute npm i, the following error message is now appearing: npm i npm ERR! path /home/ole/.npm/_cacache/index-v5/37/b4 npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall mkdir npm ERR! Error: EACCES: permi ...

What is the best way to transform an array containing diverse object types into JSON without omitting any object attributes in Swift?

Within my iOS Swift project, there arises a necessity to transform objects into JSON format. The structure includes a straightforward class: class Car : Encodable { var brand: String init(brand: String) { self.brand = brand } } c ...

Node.js seems to be playing tricks on me. It's creating bizarre names and tweets by utilizing arrays

Trying to decipher a snippet of code that is tasked with generating random tweets has left me puzzled. Specifically, I find myself stumped when it comes to understanding the line: Math.floor(Math.random() * arr.length) I believe this line selects a rando ...

Exploring the elements of Ext.js gridpanel and content components

Currently, I am diving into the world of Ext.js and finding it to be quite distinct from the asp.net ajax library despite some initial similarities. My goal is to populate a grid with test data formatted in JSON. The code snippet below illustrates my atte ...

What's the importance of including (req, res, next) in the bodyParser function within Express?

My original use of bodyParser looked like this: app.use(bodyParser.json()); However, I now have a need to conditionally use bodyParser: app.use((req, res, next) => { if (req.originalUrl === '/hooks') { next(); } else { ...

Transferring data from JavaScript to PHP with the help of AJAX

I am encountering issues with my code, as I cannot seem to successfully send coordinates from JavaScript to PHP using AJAX. Although I can retrieve values from JavaScript into a textbox, the values are not being transferred to PHP. Any assistance on resolv ...

What is the best way to apply an outer border to a table using CKEDITOR?

Is there a way to only add an outer border to an HTML table in CKEDITOR? I've attempted to remove the inner borders using the advanced options in CKEDITOR, but it doesn't seem to be working. <table border="1" cellpadding="1" cellspacing="1" ...

What causes fs to produce an error when routing to a new page, yet refreshing the page resolves the issue?

Concern: I have developed a NextJs application with 4 input fields, each connected to a predefined options list read in as a json file within the project. The user can select two fields and then proceed to a search page by clicking a button. From the sear ...

Ways to enhance a Vue component using slots

I am looking to enhance a third-party library component by adding an extra element and using it in the same way as before. For example: <third-party foo="bar" john="doe" propsFromOriginalLibrary="prop"> <template v ...

Conceal the scroll bar while still allowing for scrolling functionality

In this code snippet, I am trying to maintain the scroll position of two blocks by syncing them together. Specifically, I want to hide the scrollbar of the left block while scrolling the right one. If anyone has any suggestions or solutions for achieving ...

Deciphering click event parameters in an AngularJS application

Currently, I am in the process of improving a feature in an existing application that has already been deployed. Unfortunately, all the JavaScript code is minified, and I only have access to the HTML files. I need to implement a function that triggers when ...

Transforming a Collection of Dictionary Objects into a JSON Array on iOS

I'm looking for a way to convert an NSArray into a JSON array format so that I can send it to the server. Here is a sample of the NSArray that needs to be converted: array([0] => array('latitude'=>'10.010490', ...

Generating images using Node.js and GraphicsMagick

I'm looking for a way to generate an image using graphicsMagick and node.js. Typically, I can achieve this with the following command: gm convert -background transparent -pointsize 30 -gravity Center label:türkçee HEEEEEY.png But I need to replic ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

Recursive array generation

Given an array 'featureList', the goal is to create a new array 'newArray' based on a specific ID. For example, for ID 5, the newArray would be ['MotherBoard','Antenna','Receiver'], where Receiver correspon ...