Establishing a connection to a JSON API to retrieve and process

I am trying to extract all instances of names from this page: .

For guidance, I have been using this tutorial as a reference: . However, when I run the code provided, it doesn't return anything. What could be going wrong?

var request = new XMLHttpRequest();

request.open('GET', 'api.openparliament.ca/politicians/?format=json', true);
request.onload = function () {

  // Accessing JSON data
  var data = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
    data.forEach(politician => {
      console.log(politician.name);
    });
  } else {
    console.log('Error');
  }
}

request.send();

Answer №1

Greetings Sean and welcome to StackOverflow.

It appears that there are a few issues in your code that need to be addressed.

  • Make sure to include http:// in the URL within this line of code:
    request.open('GET', 'http://api.openparliament.ca/politicians/?format=json', true);
    .
  • You should wait for the XMLHttpRequest.readyState to reach DONE. You can check the readyState property like this:

if (request.readyState === 4) {
    // Your code goes here...
}

  • Ensure that the XMLHttpRequest returns a status code of 200. You can do this by checking:

if (request.status === 200) {
    // Your code goes here...
}

Following that, you can use the following code:

var data = JSON.parse(this.response);

Here, data is an object with two properties: objects (an array of objects) and pagination (an object).

You can then iterate through the array of objects like so:

data.objects.forEach(politician => {
  console.log(politician.name);
});

Feel free to refer to the complete demo below for more clarity:

(function() {

  var request = new XMLHttpRequest();
  request.open('GET', 'http://api.openparliament.ca/politicians/?format=json', true);
  request.onreadystatechange = function() {
    if (request.readyState === 4) {
      if (request.status === 200) {
        var data = JSON.parse(this.response);
        data.objects.forEach(politician => {
          console.log(politician.name);
        });
      } else {
        console.log('error');
      }
    }
  }

  request.send();
}());

I hope this information proves helpful.

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

Next.js encountered an API resolution issue while uploading a file, resulting in no response being

Even though my code is functioning properly, a warning appears in the console: The API call was resolved without sending any response for /api/image-upload This particular endpoint is responsible for uploading an image to Digital Ocean's object sto ...

Implementing user profile picture display in express.js: A step-by-step guide

I'm having trouble displaying the profile picture uploaded by users or employees in my application. Although the picture uploads successfully, it doesn't show up and gives an error when I try to redirect to the page. Cannot read property &ap ...

Storing JSON information in the database at a specified moment

I am interested in truncating and storing JSON data from an external URL daily at a specific time, which is 10pm. The URL requires login credentials, which I possess, but I am unsure of the best approach to take. The structure of the JSON data is as follo ...

React Component: Issue with conditional "if else" statement not refreshing in return statement

Starting out in React and the front-end field with minimal experience. Currently attempting to dynamically change the color of the "fill" property in a polygon element using React. If the percentage is greater than 50, I want the color to be green; otherw ...

Tips on creating animations for elements that are triggered when scrolling and become visible

Is there a way to animate an element when it becomes visible on scroll, rather than at a fixed position on the page? I'm currently using code that triggers the animation based on an absolute scroll position, but I'm looking for a more dynamic sol ...

How can one identify a concealed glitch that exclusively occurs for a particular individual or hardware in a React environment?

Is it possible to identify a bug that occurs only with a particular individual or hardware in a React application? This bug is invisible and never appears during tests, but only manifests with a specific client within my company. Do you have any tips on h ...

Vue not displaying information from API calls

After developing my own backend API, I encountered a strange issue. When I test the API on Chrome, it functions perfectly fine. However, when I attempt to consume the API using Axios in Vue, no data is returned. axios.get('http://192.168.149.12:8888/ ...

Setting a unique identifier for a newly created element in JavaScript and the DOM

Is there a way to assign an element ID to a newly created element using JavaScript DOM? The code I've written generates a table that is displayed when a button is clicked. I'm looking to give this table a unique ID so it can have a distinct sty ...

"The debate over using 'stringly typed' functions, having numerous redundant functions, or utilizing TypeScript's string enums continues to divide the programming

I have a specific object structure that contains information about countries and their respective cities: const geo = { europe: { germany: ['berlin', 'hamburg', 'cologne'], france: ['toulouse', ' ...

For every item in the loop, iterate through it using PHP and

Hey there! I need some help with PHP and JSON. I'm currently running this PHP code in a foreach loop, but when I try to extract all the tank IDs from the JSON file, they appear like this: 8011819314145 What I actually want is for them to display a ...

Iterate through a JSON object using JavaScript, with distinct keys but the same object structure

Hello, I'm currently in the process of creating a slider using images sourced from a json file. Here is the json structure that I am working with: { "info":[ { "slide1":[ { "title" ...

Learn the technique of looping through multiple HTML elements and wrapping them in Vue.js easily!

i need to wrap 2 HTML elements together Here is my code snippet using Vue.js <tr> <th v-for="(item9,index) in product_all" :key="item9.id"><center>Qty</center></th> <th v-for="(item99,index) in product_all" :key=" ...

Performing two API calls using Jquery to fetch distinct dynamic elements within two nested $.each loops

There's an API link that contains crucial data about phone brands. From this initial data, I have to create a second API call for each brand to gather more detailed information. For example, the first JSON file (urlphonebrands) lists 3 phone brands - ...

What is the method to verify if a variable in ES6 is constant?

I'm seeking advice on how to accomplish a specific task. I attempted using the try-catch method, but encountered some limitations: "use strict"; const a = 20; var isConst = false; try { var temp = a; a = a+1; a = temp; } catch (e) { isConst = ...

Constantly positioning the text cursor over the Textbox

I am currently in the process of developing a webpage that will feature only one text box for displaying information based on the input data provided. Our strategy involves utilizing either a Barcode Scanner or Magnetic Swipe as well as a Touch Screen Moni ...

Exploring nested JSON or dictionary to find multiple key values that match the defined keys

I'm grappling with a Python object that has multiple layers of dictionaries and lists, each containing keys from which I need to extract values. I stumbled upon an interesting solution involving recursive generators that allows me to fetch the value o ...

Chrome PWA debugger fails to respond when attempting to use the "add to homescreen" button

I have been endeavoring to implement the "add to Homescreen" prompt feature on my website. After thoroughly reviewing Google developer documentation, I have successfully configured everything accordingly. However, when I try to manually add my page to the ...

Can you explain the significance of the sentinel value NULL mentioned in the Android Developer JSONObject reference page?

Can you explain the significance of the sentinel value NULL in Android Developer JSONObject reference page? Here is an excerpt from the page for reference: The class represents null in two incompatible ways: the standard Java null reference, and the senti ...

Extracting a dynamic parameter from a JSON object

Hey there, I'm new to JavaScript and have been searching for answers online for hours with no luck. I have a question regarding calling an API and receiving the following result: { "return_status":1, "return_message":"success", "data":{ ...

The public folder in Node.js is known for its tendency to encounter errors

I'm facing an issue with displaying an icon on my website. Here is the current setup in my code: app.js const http = require('http'); const fs = require('fs'); const express = require('express') const path = require(&apo ...