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

How to manage multiple items within a single MUI/React TextField

Recently diving into the world of JS, React, and MUI, I find myself faced with a challenge involving a MUI TextField that is supposed to handle multiple values. For example: 1*10 5*50 13*250 5*50 1*10 3*33.33 4*25 3*33.33 All on a single line. These ...

My Next.js application is successfully making Axios API calls to my localhost while running on the server-side

In my Next.js and React application, I am utilizing the axios library. Initially, I was able to successfully call the API from the server using getStaticProps() and render the initial data properly. However, when attempting to fetch more data from the clie ...

Stuffing a container with an image without considering the proportions

I am experimenting with filling a parent <div> with an image without concern for proportions. Despite knowing that it may not look great at all sizes, I just want to test its feasibility. Currently, the image is scaling instead of stretching to fit m ...

Guide on effectively sending a secondary parameter in an ajax request

Struggling to implement a year/make/model multi-select feature, I have managed to get the scripts working. However, what appears to be missing is the ability to pass both a year and make variable together in order to fetch the final model results. Below a ...

What could be the reason behind TypeScript ignoring a variable's data type?

After declaring a typed variable to hold data fetched from a service, I encountered an issue where the returned data did not match the specified type of the variable. Surprisingly, the variable still accepted the mismatched data. My code snippet is as fol ...

Having trouble with the anchor tag not functioning properly

I'm looking to create a unique video experience by having an iframe video play automatically and opening a third-party video player in a lightbox style when clicked. Currently, the video autoplays, but I want it so that when the user clicks on the vi ...

Exploring the distinctions between ajax, await, async, and

English is not my strong suit, so please bear with me if my writing seems odd. We have discovered two methods for transitioning from asynchronous ajax calls to synchronous ones. Using async: false Utilizing await Both achieve the same outcome, but I am ...

Can an array be used as valid JSON for a REST api?

Utilizing MongoDB with Mongoskin in a web application using Node.js allows for the execution of .find() on a collection to retrieve all documents within it. The result returned is a mongodb cursor. To convert this cursor into an Array, you can utilize the ...

When working with NextJs, you may encounter a ValidationError indicating that the configuration object is invalid. This error occurs when Webpack has been initialized with a configuration object that doesn't

After upgrading from Next v12 to v12.2.3, I encountered a problem when running "yarn dev" with a new middleware.js file in the root directory: ValidationError: Invalid configuration object. Webpack initialization error due to mismatched API schema. - Deta ...

What is the best way to send props from page.js to layout.js in the Next.js app directory?

Is there a way to effectively pass props to layouts in Next.js 13? Can we optimize the approach? Here's an example: // layout.js export default Layout({children}) { return ( <> {/* Display different `text` based on the page.js being ...

Ways to eliminate the worldwide model in SAPUI5

I've been attempting to break down the global model without success. I have a filter button that's set up like this: navToSecond : function (oEvent){ var oObject = this.getView().byId("inp").getValue(); sap.ui.getCore().setModel( ...

Refresh only a portion of a page using PHP and JavaScript

I have a webpage set up with multiple sections in separate divs. Currently, the essential divs required are <div id="main">...</div> & <div id="sidebar">...</div> Each div contains PHP code like: <?php include("page.php") ...

Trigger a unique event using Vanilla JS and then detect it on Vue instances

I am currently in the process of incorporating multiple Vue instances into my website. I have encountered issues preventing me from making the entire website a Vue instance and using components due to potential conflicts and other complications. For examp ...

Add a click event listener to the body element using a button click, without causing it to trigger

What is the current situation: A button is clicked by the user The menu opens (list items display = block) The function to close the menu is connected to the <body> The function to close the menu is immediately triggered, causing the menu to close ...

Creating a wrapper class in Express JS: A step-by-step guide

I am currently developing a basic wrapper app that retrieves the following information from user requests: a) Request Date & Time b) Request URL c) Response Time This is my approach to wrapping the functionality using Express.js: var express = require(&a ...

Is there a way to extract rows from a React MUI DataGrid that are identical to how they are displayed, including any filtering and sorting applied?

My goal is to make a selected row move up and down on arrow clicks, and in order to achieve this, I need to retrieve rows from the MUI DataGrid. I am using the useGridApiRef hook to do so, ensuring that the rows are filtered and sorted accordingly to match ...

Trigger the jQuery function based on the ID modification executed by jQuery

Is it possible to change the id of an HTML element using this function? $("#test").attr('id', 'test2'); Here is an example of the code: $("#test").click(function() { $("#test").attr('id', 'test2'); alert(& ...

Updating the JSON data with a new row

I am trying to dynamically add a new row to my JSON data when the user clicks on a link. Despite not receiving any errors, I am unable to see the updated JSON in my alert message. $(document).ready( function(){ people = { "COLUMNS":["NAME","AGE"], ...

The connection was refused by hapi.js

We have recently encountered an issue while using hapijs: hapi, {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","domainEmitter":{"domain":{"domain":null,"_events":{},"_maxListeners":10,"members":[]},"_events":{},"_maxListeners":10},"doma ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...