What is the best way to extract JSON data from a remote URL?

Having recently started with JavaScript, I am looking to parse JSON from an external URL using pure JavaScript. Currently, I have the following code:

var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status === 200) {
    callback(null, xhr.response);
  } else {
    callback(status, xhr.response);
  }
};
xhr.send();
 };

 function statsget() {
 var uname = document.getElementById("nameget").value;
 var data = getJSON(`https://www.reddit.com/user/${uname}/circle.json`);
 var stats = JSON.parse(data);
 alert(data.is_betrayed);
 }

However, this implementation is not functioning as expected. Is there anyone who could assist me in resolving this issue? Thank you!

Answer №1

Initially, it appears that you overlooked passing a callback function to getJSON as the second parameter, which should be executed when your request returns with the data. Additionally, there is no need to manually parse the data to JSON when requesting a JSON file from the server and setting the responseType to JSON; this process will be handled automatically for you.

var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status === 200) {
    callback(null, xhr.response);
  } else {
    callback(status, xhr.response);
  }
};
xhr.send();
 };


function yourCallBackFunction(err, data){
    if(err){
        //Handle the error 
    }else{
        //The data variable holds the JSON response received from the server
    }

}

 function statsget() {
 var uname = document.getElementById("nameget").value;
 var data = getJSON(`https://www.reddit.com/user/${uname}/circle.json`, yourCallBackFunction);

 }

If you require further clarification on any aspect, feel free to ask.

Answer №2

If you're looking to utilize pure Javascript, there is a handy built-in method available that eliminates the need for creating your own function:

 function fetchData() {
   var username = 'CertainPerformance';
   fetch(`https://www.reddit.com/user/${username}/data.json`)
     .then(response => response.json())
     .then(jsonResponse => {
       // manipulate jsonResponse here
       console.log(jsonResponse);
     });
 }
 fetchData();

Promises offer a more streamlined approach compared to traditional callbacks.

Answer №3

Make sure to have a callback function specified within your statsget process. It should look something like this.

function statsget() {
 var username = document.getElementById("nameget").value;
 getJSON(`https://www.reddit.com/user/${username}/circle.json`, 
    function(data) {
      var statistics = JSON.parse(data);
      alert(data.is_betrayed);
    });
}

Answer №4

The reason it's not working as expected is likely due to the fact that you are not utilizing the callback function, even though it is included as a parameter in your getJSON function.

In order for this function to be executed after receiving a response, you need to include something like the following:

var processData = function(status, data){
    console.log("Data received:\n", data);
    if(status == null) { 
       return data;
    }
}

function fetchData() {
     var username = document.getElementById("nameInput").value;
     var responseData = getJSON(`https://www.reddit.com/user/${username}/data.json`, processData);
     var parsedData = JSON.parse(responseData);
     alert(parsedData.is_betrayed);
}

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

Automatically load content using AJAX when scrolling within a HTML5 segment

Recently, I've been developing a website that dynamically loads new content from a MySQL database as the user scrolls. However, I've encountered an issue where the new content is loaded even with minimal scrolling, rather than only when reaching ...

Instructions on integrating a column of buttons into a Bootstrap table containing information retrieved from a MySQL database

My bootstrap table is currently displaying data that is loaded from a MySQL database. I am looking to enhance it by adding a column with buttons, similar to the layout shown in this image. https://i.stack.imgur.com/8fWfR.png However, I am facing some dif ...

Retrieving data from JSON arrays based on specific conditions in Java

I have been utilizing Unirest to retrieve all IDs from an endpoint. The array structure is as follows: [ { "date": "2022-04-05", "timeIn": "2022-04-05 07:00:00", "timeOut": " ...

SyntaxError: JSON parsing error - encountered an unexpected character at the beginning

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); const fs = require("fs"); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // http://expressjs.com/en/starter/static-files ...

Building a dynamic map with React components using an array

Using the passed ID, a new element is dynamically generated: const Icon: FC<IconPropsI> = ({iconId, ...rest}) => { const iconsMap: IconsMapT = { IconUser: IconUser, IconTime: IconTime, IconVideo: IconVideo } return createElement ...

modify the content of a json file by substituting a specific value with bash

I'm dealing with multiple .json files that have a similar structure. { "AcquisitionNumber": 1, "TotalReadoutTime": 0.035, "IntendedFor": "func/sub-02_task-rest_run-01_bold.nii.gz" } My goal is to alter the sub number in the "IntendedFor" ...

Tips for effectively passing query string parameters in Angular

I am looking to make an HTTP request with parameters through a query For instance: URL: https://api/endpoint?d=1&value=2 ...

Node JS Axios Network Error due to CORS Policy Restrictions

When attempting to make a put axios request, I encounter the following error: I have installed and enabled the CORS module in the server.js file, but it doesn't seem to be working. Additionally, there are no CORS headers in the request: In the serve ...

"Exploring the process of retrieving data from a request in Node.js with the help of the Express

I'm encountering some issues with integrating a "login" form into my Node.js script. While I can get it to work using a static HTML page, utilizing a dynamic ".ejs" page is causing trouble as my form fields are showing up as "undefined". var helmet = ...

Update the JSON data based on the specifications outlined in my project

class Transformation { constructor() { this.colHeaders = { error_description: "Description", error_status: "Status", error_code: "Error Code" }; } getColHeader() { return this.colHeaders; } } var jsonData = { error ...

Using the getAttribute method in Edge with JavaScript

My goal is to dynamically load videos on the page after it has fully loaded. I have a script that successfully works in Firefox and Chrome, but I encounter errors when using Edge/IE. The specific error message I receive is SCRIPT5007: Unable to get propert ...

Tips for integrating custom code into your Angular cli service worker

Although I have successfully generated and configured the service worker using a config file generated by Angular CLI, I am struggling to find documentation on how to add custom code to the ngsw-worker.js file. I want to include functions such as push no ...

Issue with long text in a resizable table using jQuery tablesorter 2.31.1

My issue is that when I try to resize the columns in tablesorter, they snap back into place. The column width set with resizable_widths does not apply correctly until a column is manually resized. Despite setting the width of all cells to 120px, any cells ...

Having trouble with the rendering of the Stripe Element Quickstart example

Currently, I am diving into the world of Stripe's Element Quickstart. Take a look at this fiddle that I have been working on. It seems to be quite different from the example provided. Although I have included the file, I can't seem to figure out ...

Switching from using a computed property in Vue 2 to implementing the Vue 3 Composition API

I am currently in the process of updating my Vue 2 application to Vue 3 and I have been exploring how to work with computed properties using the Composition API in Vue 3. One particular challenge I am facing is migrating a Vue 2 computed property that pro ...

Verify the presence of an email in the database utilizing a custom express-validator for node, express, and mysql

//Endpoint to update the user's email address. apiRouter.post('/update-email', [ check('newEmail') .isEmail().withMessage('Please enter a valid email address') .custom(newEmail=> { db.query(`SELECT user ...

Struggling with this mixed content problem

Encountering a problem while loading a js file: https://code.jquery.com/jquery-1.11.1.min.js, which is being loaded on my webpage in this manner: <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> Upon loading my webpage, an ...

Currently, I am working on a project and encountering an issue with html2canvas

const handleDownloadImage = async () => { try { const canvas = await html2canvas(cardRef.current); console.log(cardRef.current); const imageData = canvas.toDataURL("image/png"); setImageUrl(imageData); } catch ( ...

When the radio button is selected, show a variety of buttons

I'm facing an issue with rendering different buttons for two radio buttons within a view. Here is the rendered HTML code for the radio buttons: <input checked="checked" id="Isattending_0" name="Isattending" type="radio" value="Yes" /> <inpu ...

load a file with a client-side variable

Is there a way to load a file inside a container while utilizing an argument to fetch data from the database initially? $('#story').load('test.php'); test.php $st = $db->query("select * from users where id = " . $id); ... proce ...