Accessing information from JSON files using AJAX

I'm currently working on loading data from a JSON file using AJAX. The file I'm referencing is external-file.json. Within the code snippet provided, there are other unrelated sections. I'm encountering an issue within the getViaAjax function and I'm struggling to identify the error.

function flip(){
    if(vlib_front.style.transform){
        el.children[1].style.transform = "";
        el.children[0].style.transform = "";
    } else {
        el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
        el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
    }
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');

el.addEventListener('click', flip);

var word = null; var explanation = null;

var i=0;

function updateDiv(id, content) {
    document.getElementById(id).innerHTML = content;
    document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])

function counter (index, step){
    if (word[index+step] !== undefined) {
        index+=step;
        i=index;
        updateDiv('the-h',word[index]);
        updateDiv('the-p',explanation[index]);
    }      
}

var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
    counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
    counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
    var r = new XMLHttpRequest();
    r.open("GET", "external-file.json", true);
    r.onload = function() {
        if(this.status < 400 && this.status > 199) {

            if(typeof callback === "function")
                callback(JSON.parse(this.response));
        } else {
            console.log("err");// server reached but gave shitty status code}
        };
    }
    r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}

    r.send();
}

function yourLoadingFunction(jsonData) {
    word = jsonData.words;
    explanation = jsonData.explanation;
    updateDiv('the-h',word[i]);
    updateDiv('the-p',explanation[i])
    // then call whatever it is to trigger the update within the page
}

getViaAjax("external-file.json", yourLoadingFunction)

Answer №1

In agreement with @light's statement, this can be seen as:

function fetchWithAjax("external-data.json", handler) { // specifying the URL of the external JSON file
  var request = new XMLHttpRequest();
  request.open("GET", "external-data.json", true);

The revised version should look like this:

function fetchWithAjax(url, handler) { // specifying the URL of the external JSON file
  var request = new XMLHttpRequest();
  request.open("GET", url, true);

Answer №2

In case you need help isolating your issue, I have created a sample that you can use. Simply set it up on a local http-server of your choice, and when you run it, you will see that JSON.parse(xhr.response) will give you a JavaScript array with two objects.

There are two files included:

  1. data.json
  2. index.html

data.json

<html>
    <head>
    </head>
    <body onload="so.getJsonStuffs()">
        <h1>so.json-with-ajax</h1>
        <script type="application/javascript">
        var so = (function(){

            function loadData(data){
               var list = document.createElement("ul");
               list.id = "data-list";
               data.forEach(function(element){
                   var item = document.createElement("li");
                   var content = document.createTextNode(JSON.stringify(element));

                   item.appendChild(content);
                   list.appendChild(item);
               });
               document.body.appendChild(list);
           }

            var load = function()
            {
                console.log("Initializing xhr");
                var xhr = new XMLHttpRequest();

                xhr.onload = function(e){
                    console.log("response has returned");
                    if(xhr.status > 200
                    && xhr.status < 400) {
                        var payload = JSON.parse(xhr.response);
                        console.log(payload);
                        loadData(payload);
                    }
                }
                var uri = "data.json";
                console.log("opening resource request");
                xhr.open("GET", uri, true);
                xhr.send();
            }

            return {
                getJsonStuffs : load
            }
        })();
        </script>
    </body>
</html>

Upon running this code, two JavaScript objects will be logged in the Developer Tools console. Additionally, a ul element will be added to the DOM, containing a list item for each object in the data.json array.

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

Creating a Dynamic Cascading Dropdown Menu in ASP.Net MVC2

Currently working with mvc2 and c# ASP.Net, I am attempting to incorporate cascading dropdown lists. The first dropdown is labeled as "group" and the second one as "division". When selecting a group, its respective divisions should be displayed in the seco ...

Difficulty reloading after updating input using AngularJS ngTable

I'm encountering an issue where I need to utilize ngTable with TableParams to load and modify a table. For instance, when the page initializes, entering a number in the textbox for the first time displays the appropriate number of rows in the table. ...

Sticky header/navigation bar implementation in React Native for consistent navigation across views

Currently, I am working on creating a consistent navbar/header for my React Native app. At the moment, when I switch between views in my code, the entire interface changes. It functions properly, but the navbar/header scrolls along with the view, making i ...

Model of Objects within a Document

Here's a puzzling question for you: why does console.log(document.body) and console.log(document.head) work perfectly fine, but console.log(document.script) or console.log(document.html) don't seem to do anything? It's strange because all of ...

Angular: Enhancing URL links

Recently, I discovered a function in my code that allows me to cycle through different pictures and change the URL accordingly. The initial URL is obtained using angular routes, where the "domain" parameter consists of the domain.id and the domain.category ...

Debouncing in AngularJS with $watch

In my code, I have an HTML search field represented by the following: <input ng-model-options="{ debounce: 500 }" type="text" ng-model="name"> Along with the JavaScript snippet: $scope.$watch('name', function(newVal, oldVal) { ...

What is the best method for interpreting XML using JavaScript?

I am facing a challenge with fetching and parsing an XML file using JavaScript. The XML-file is beyond my control. Recently, there has been a change in the encoding of some XML files which prevents the code from being parsed successfully. Previously it wa ...

The issue of data not being transmitted when an ajax jquery form is modified

Each item in the cart/order has its own unique form with IDs created in a loop (e.g. 'id'=>'cart_'.$line )(cart_1,cart_2), along with an update link for each form within the loop. See the code snippet below: echo form_open($control ...

Loading slides in bxSlider using ajax

Is there a method to dynamically insert a slide into bxSlider via ajax without affecting its smooth transition? I am looking to initially display the contents of only one slide upon page load, and then have subsequent slides loaded when the next or previo ...

Merging arrays with the power of ES6 spread operator in Typescript

My goal is to merge two arrays into one using the spread object method as shown in the code snippet below: const queryVariable = { ...this.state, filters: [...Object.keys(extraFilters || {}), ...this.state.filters], } The this.state.filte ...

Is the `visibility: hidden` property not functioning as expected?

I am trying to conceal the script for the photoset until it is fully loaded, but unfortunately the code below does not seem to be effective: JavaScript $('.photoset-grid').photosetGrid({ rel: $('.photoset-grid').attr("data-id"), gutte ...

Node.js' Express WebSocket adds complexity to JSON with additional characters

In my configuration, I have set up a nodeJS server using Express and BodyParser. const express = require('express') const expressWs = require('express-ws') const bodyParser = require('body-parser') app.ws('/ws', web ...

Experiencing a problem with a loop structure in my code

I've been trying to create a loop that will increase the temperature by 10 degrees every 2 minutes. However, I'm struggling to figure out how to stop the temperature at 120 degrees after 16 minutes. Any suggestions on how to solve this issue? va ...

Simulate a keyboard key being pressed and held for 5 seconds upon loading the page

Is it possible to create a script that automatically triggers an event to press and hold down the Space key for 5 seconds upon page load, without any user interaction? After the 5 seconds, the key should be released. It is important to emphasize that abso ...

The functionality of a switch statement relies on the presence of a React-Router

Is there a way to dynamically change the text in a paragraph based on which Route is currently enabled? I tried using a switch statement, but I'm unsure of how to implement it. Any suggestions or ideas? import React from 'react'; import &ap ...

How can a JavaScript function be imported into a React component from a location outside the src folder?

I have a utility function in my JavaScript utils.js file within the Django static files. I am looking to make this file accessible for use with React as well. I would like to import this file along with its functions into a React component. Here is an ex ...

Tips to avoid conflicts between endpoints when building a REST API in an Express application

I am currently working with a REST API in an Express application to retrieve orders. http://localhost:2000/api/orders/chemists?orderBy=date&startDate=date1&endDate=date2 http://localhost:2000/api/orders/chemists?orderBy=chemist&startDate=date ...

The input '{ data: InvitedUser[]; "": any; }' does not match the expected type 'Element'

I'm currently facing a typescript dilemma that requires some assistance. In my project, I have a parent component that passes an array of results to a child component for mapping and displaying the information. Parent Component: import { Table } fr ...

Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeati ...

What's the best way to retrieve the id or index of a card within a list?

Struggling to fetch the id's of documents retrieved from a MongoDB database and displayed on React and Material-Ui cards. Tried logging id in functions and APIs, but receiving 'undefined' or metadata from the delete function. Delete functi ...