Acquire JSON data from a URL and display it on the webpage

I'm facing an issue where the JSON data I'm trying to fetch from a URL is not displaying due to an uncaught reference error in my code. How can I modify the code to ensure that the data gets shown?

var url = "https://fantasy.premierleague.com/api/entry/1258872/";

req.open("GET", url);
req.send();

req.addEventListener("load", function(){
if(req.status == 200 && req.readyState == 4){
  var response = JSON.parse(req.responseText);
    document.getElementById("id").textContent = response.title;
    document.getElementById("player first name").textContent = response.player_first_name;
     document.getElementById("player last name").textContent = response.player_last_name;
  }
})
<h1>Fantasy Premier League</h1>
<h2 id="id"></h2>
<h3>First Name: <span id="player first name"></span></h3>
<h3>Last Name: <span id="player last name"></span></h3>

Answer №1

It is crucial to initialize your request req object before invoking the open method

var req = new XMLHttpRequest();

If you attempt to call a method on an undefined object like in your case with req, it will result in an error being thrown

A more refined version of your code should look like this:

var url = "https://fantasy.premierleague.com/api/entry/1258872/";
var req = new XMLHttpRequest();

req.onreadystatechange =  function() {
    if(req.status == 200 && req.readyState == 4){
         var response = JSON.parse(req.responseText);
         document.getElementById("id").innerText = response.title;
         document.getElementById("player first name").innerText = response.player_first_name;
         document.getElementById("player last name").innerText = response.player_last_name;
  }
};

req.open("GET", url);
req.send();

Answer №2

Don't forget to announce the XMLHttpRequest object. However, bear in mind that it may not return a response from the api due to its cors policy.

var URL = "https://fantasy.premierleague.com/api/entry/1258872/";

var request = new XMLHttpRequest();
request.open("GET", URL);
request.send();

req.addEventListener("load", function(){
if(request.status == 200 && request.readyState == 4){
  var response = JSON.parse(request.responseText);
    document.getElementById("id").textContent = response.title;
    document.getElementById("player first name").textContent = response.player_first_name;
     document.getElementById("player last name").textContent = response.player_last_name;
  }
})
<h1>Fantasy Premier League</h1>
<h2 id="id"></h2>
<h3>First Name: <span id="player first name"></span></h3>
<h3>Last Name: <span id="player last name"></span></h3>

If you wish to fetch the data and bypass the cors policy, consider making the request using server-side scripting like PHP:

$contents = 
file_get_contents("https://fantasy.premierleague.com/api/entry/1258872/");
echo $contents;

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

Querying Parse Server for objectId information

Within my web app that utilizes the Parse Server Javascript SDK, I have implemented the following query. While the console log accurately displays the retrieved information, the objectId field appears as "undefined." var query = new Parse.Query("myClass") ...

When using AutoComplete in MUI, I encountered an issue while attempting to assign a default value to the checkbox from an API. Instead of achieving the desired result, I received an error stating "(inter

Within this snippet, I am seeking to retrieve a default value from the API to populate a checkbox initially. I have employed the Material-UI Autocomplete component, which includes a defaultValue prop. Despite my efforts to utilize this prop, I am encounter ...

Filtering nested arrays in Javascript involves iterating through each nested

I have a nested array inside an array of objects in my Angular app that I'm attempting to filter. Here is a snippet of the component code: var teams = [ { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name ...

The method defined in user.model.js cannot be utilized in mongoose and node

When developing an app with node and mongoose, I encountered a peculiar issue while testing. Below is my auth.index.js file for user login. auth.index.js: var express = require('express'); var mongoose = require('mongoose'); var passp ...

Utilizing Navigate and useState for Conditional Routing in React

Looking for assistance with a React app. Here's the code snippet: function App() { const [walletConnected, setWalletConnected] = useState("") async function checkConnection() { const accounts = await window.ethereum.request({ method: 'e ...

What is the process for importing JSON data into Node.js following the bundling of the entire server as an executable using the "pkg" compiler?

When running my node.js environment with "npm start", I am able to require/import JSON files and access the data inside without any issues. For instance, if I have a file named "./Assets/port.json" containing {"port": 3000}, I can import it and retrieve t ...

Is it possible to update labels on an AngularJS slider using a timeout function?

I recently started implementing an AngularJS slider to navigate through various date and time points. Specifically, I am utilizing the draggable range feature demonstrated in this example - https://jsfiddle.net/ValentinH/954eve2L/ The backend provides the ...

Selenium in Perl: Facing a puzzling JavaScript error while attempting to resize window

Utilizing the Perl Selenium package known as WWW::Selenium, I have encountered a perplexing JavaScript error while attempting to resize the browser window. The error message reads: "Threw an exception: missing ; before statement". Below is the code snippe ...

Configuring Angular routes based on service method invocation

I have my routes configured in @NgModule. I also have a service that determines which parts of the application to display based on specific conditions. I need to call this service and adjust the routes according to its output. Issue: The route configurati ...

Retrieve four distinct values using only a single text box input and display them individually on separate lines

Is there a way to receive four input values from the user using just one textbox and display them on separate lines? function collectData() { var userInput, i; var textOutput = " "; for (i = 0; i <= 3; i++) { userInput = document.g ...

Transforming the JSON data into a text format

I have a JSON object structured like this: { "name": "ok", "country": "US", "phone": "900", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f70745f727e767331707c">[email protected]</a>", ...

I'm looking for recommendations on where to begin learning about JavaScript touch events for web development. Any suggestions?

Seeking guidance on creating image galleries and content sliders that work with both touch and mouse events. Where should I begin exploring touch event implementation? I'm having difficulty locating official documentation. Are there any jQuery-suppo ...

Troubleshooting JavaScript Functions Failure Following AJAX XML Request

My current project involves developing an interactive map where users can select a year from the timeline and apply filters. This functionality is achieved through XML HttpRequest, which refreshes the SVG each time a selection is made. The SVG code for th ...

What's the best way to customize the color of the text "labels" in the Form components of a basic React JS module?

I have a React component named "Login.js" that utilizes forms and renders the following:- return ( <div className="form-container"> <Form onSubmit={onSubmit} noValidate className={loading ? 'loading' : ''}&g ...

Problems encountered when attempting to create a link between two nodes on a force-directed graph using a mouse click

I'm currently working on creating an interactive graph where users can click on two nodes to establish a link between them (which can be removed later). My approach was inspired by Mike Bostock's example at: https://bl.ocks.org/mbostock/1095795 ...

A step-by-step guide to setting up a Slick Slider JS slideshow with center mode

I am working on implementing a carousel using the amazing Slick Slider, which I have successfully used for images in the past without any issues. My goal is to create a 'center mode' slideshow similar to the example provided but with multiple div ...

Developing a new class within a function

In this section of the HTML file, I have set up a form to collect email and password information from new users in order to create a new profile: <form name="userInfo"> <fieldset> <legend>Create a new account</legend> ...

Tally the quantity of items within a JSON array

When using the GET method to access a JSON file, my code looks like this: $scope.train = function () { var url = 'http://localhost/heart/api/restApiController/dataset.json'; $http({ method: 'GET&apo ...

The FormData() object in Django backend is consistently found to be void of any data

I am currently experimenting with uploading an HTML form through AJAX using pure JavaScript, without jQuery. The form is put together in my template by combining three components: the CSRF token, a ModelForm, and a regular Django form (forms.Form). The vis ...

Having difficulty choosing an item from a personalized autocomplete search bar in my Vue.js/Vuetify.js project

NOTE: I have opted not to use v-autocomplete or v-combobox due to their limitations in meeting my specific requirements. I'm facing difficulties while setting up an autocomplete search bar. The search functionality works perfectly except for one mino ...