Utilizing Javascript to Parse Json Information

For my latest project, I am attempting to retrieve JSON data from a specific URL and display it on a web page using only JavaScript.

This is all new to me. Can someone assist me in fetching the JSON data from the following link:

I have been experimenting with AJAX based on some research, but so far I haven't found the right solution:

 $(document).ready(function () {

 $('#retrieve-resources').click(function () {
 var displayResources = $('#display-resources');

 displayResources.text('Fetching data from JSON source...');

 $.ajax({
 type: "GET",
 url: "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo",
 success: function(result)
 {
 console.log(result);
 var output="<table><thead><tr><th>LNG</th><th>GEONAMEID</th><th>COUNTRYCODE</th></thead><tbody>";
 for (var i in result)
 {
 output+="<tr><td>" + result.geonames[i].lng + "</td><td>" + result.geonames[i].geonameId + "</td><td>" + result.geonames[i].countrycode + "</td></tr>";
 }
 output+="</tbody></table>";

 displayResources.html(output);
 $("table").addClass("table");
 }
 });

 });
});

Answer №1

Utilize XMLHttpRequest for fetching data, as shown below:

function fetchData(){
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          document.getElementById("output").innerHTML = request.responseText;
      }
  };
  request.open("GET", "http://api.example.com/data", true);
  request.send();
}

fetchData()

You can also opt for promise-based libraries like axios:

Include the library

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Sample code using axios:

function fetchData(){
  var response = axios.get('http://api.example.com/data')
  document.getElementById('output').innerHTML(response.data)
}

fetchData()

Answer №2

When integrating AJAX with external resources, ensure JSONP is being utilized.

$.ajax({
    type: "GET",
    url: "http://api.geonames.org/citiesJSON?",
    dataType: "jsonp",
    data: { .. },
    success: function( response ) {
        console.log( response );
    }
});

Here's a JQuery example and an example from StackOverflow. Also, check out this informative article on JSONP.

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

Error encountered when attempting to serialize object to JSON due to circular reference detection

As discussed in this particular post, a Json serialization error is being encountered during the serialization of an Entity Framework Proxy: The issue indicates a circular reference while serializing an object of type 'System.Data.Entity.DynamicP ...

What is the best way to trigger a unique modal dialog for every element that is clicked on?

I simply want to click on the state and have that state's specific pop-up appear. $("path, circle").on('click', function(e) { $('#info-box').css('display', 'block'); $('#info-box').html($(this ...

Using Google Maps: How can I trigger an InfoWindow to open by hovering over a link?

Trying to figure out how to make the "info window" on my map pop up when hovering over a corresponding link in the list of points. Currently, you have to click on a point to see the information. Any suggestions on how to achieve this while ensuring that al ...

Is there a way to effortlessly refresh the WooCommerce cart and receive updated HTML content all in one go?

I am currently working on a customized "mini-cart" that mimics the functionality of the main cart page, including options to adjust quantity, remove items, enter coupons, and remove coupons. I have set up the cart to submit changes via Ajax by listening fo ...

Using jQuery Ajax to Retrieve Inner Text from Elements

Looking for a solution with PHP file output like this: <div id="title">Add Us On Myspace!</div><img id="image" src="http://i39.tinypic.com/67jybs.png" alt="Add Us On Myspace!" /> The code to retrieve and display this is as follows... $ ...

Stop allowing special characters in Ajax requests (HTTP)

$.ajax({ url: '/pos/' + myVar type: 'GET', success: function(data) {} .. I have a variable called myVar with a value of "a-b". However, the value may sometimes be represented as "a->b", causin ...

Despite population, MongooseJS still renders blank array

Currently in the process of developing an application using Node.js with MongooseJS as the middleware for handling database operations. Encountering an issue with nested schemas, specifically with one of them being populated incorrectly. Despite tracking ...

jq filter to exclude certain values in select statement by matching against an array of values

Given this JSON input : { "hostname": "server1.domain.name\nserver2.domain.name\n*.gtld.net", "protocol": "TCP", "port": "8080\n8443\n9500-9510", "component": ...

Inquiring about how to retrieve a complete list of elements from a Rest Api and convert it from a json string to a list of java objects

I am currently attempting to make a Get request using RestTemplate in order to fetch a list of all objects from a basic Rest Api. This particular page outlines two methods to accomplish this (section 3.1 and 3.2) at this link. I have tested both options, ...

Encountering CORS problems when sending a request containing JSON data in the body

I have a local react application running on port 3000 and an express server running on port 8000. I am trying to make a request from within my react app as follows: fetch('http://localhost:8000/login', { method: 'POST', headers ...

What is the best way to properly format the retrieved JSON string using Ext JS?

After receiving the JSON data shown below, I need to change the formatting of the string values in the 'code' field. For example, 'TOTALPENDING' should display as "Pending Bonus" and 'TOTALLEFT' as "Current Bonus". How can I m ...

Is there a way to enable sync mode on dynatree?

I am currently utilizing the Dynatree by Martin Wendt and I am looking to update the tree dynamically and recursively using Ajax. In order to achieve this, I have incorporated functions like tree.getNodeByKey(nodes[i-1]).appendAjax({}); and tree.activateK ...

Using Regex with JavaScript while ignoring letter case

I am trying to extract a query string from my URL using JavaScript, and I need to perform a case-insensitive comparison for the query string name. In order to achieve this, here is the code snippet that I am currently using: var results = new RegExp(&apos ...

The asynchronous request sent to the API action in MVC does not trigger the success event (ASP.NET Web API)

The response from the API action is shown here. I have written a web API action as shown below and it works fine when called via an AJAX request. However, I am facing an issue where the AJAX request does not return a success result even though the action p ...

What is the best way to get jsDoc "import" to function properly in vscode?

Is it possible to import a node module using @import in Visual Studio Code? I'm trying it but it doesn't seem to be recognized. Am I missing something? https://i.stack.imgur.com/zq1rz.png ...

Tips for avoiding Client DOM XSS vulnerability in JavaScript

Upon completing a checkmarx scan on my code, I received the following message: The method executed at line 23 of ...\action\searchFun.js collects user input for a form element. This input then passes through the code without proper sanitization ...

Transferring items between different containers without using innerHTML

I've got an embedded <ul> within a (hidden) <aside id="idDetails">. How can I move the ul element from inside the aside and position it in a <div id="projectSide"> without using innerHTML? Any solutions in both plain JavaScript and j ...

Discovering the technique to interact with obscured objects through a haze of PointsMaterial in three.js

Is there a property that allows objects behind a fog of multiple points to be clickable? I want to be able to click on objects even when they are obscured by the fog. Below is the code I am using to create and animate the fog: const loadFogEffect = () =&g ...

Does the resolve function within a Promise executor support async operations?

I'm trying to wrap my head around the following code: function myPromiseFunc() { return new Promise((resolve) => { resolve(Promise.resolve(123)); }); } We all know that the Promise.resolve method immediately resolves a Promise with a plain ...

Encoding in AJAX Post Requests

In my latest project, I am developing an HTTP server in C++ and using jQuery to send Ajax POST requests to it. One specific page includes a form that is submitted with the following code: $('#create-event form').submit(function(e) { var pos ...