Pull JSON data from an Ajax application and cycle through the JSON values in a separate function

As I delve into the world of Ajax, I find myself grappling with a particular issue - the feasibility. My current endeavor involves fetching data from a db.json file using Ajax.

{
  "transactions": [
{
  "date": "4/3/2021",
  "description": "Electric bill",
  "type": "Debit", "amount": 250.00
},
{
  "date": "1/15/2022",
  "description": "Venmo",
  "type": "Debit",
  "amount": 80.00
}
  ]
}

The Ajax function triggers on window.onload

window.onload = function () {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    jsonObj = JSON.parse(this.responseText);
        return jsonObj;
  }
};
ajax.open("GET", "../titan-bank/db.json", true);
ajax.send();

Following this, the JSON file is expected to be transmitted to a specific class for iteration and subsequent display of information.

var transactions = new Transactions;
transactions.getTransactions();

var transactionDisplay = $("transactionDisplay");

class Transactions {
constructor (date, description, type, amount) {
    this.date = date;
    this.description = description;
    this.type = type;
    this.amount = amount;
}
getTransactions () {
    for (let id of values) {
        //adds index for each transaction
        var index = values.indexOf(id) + 1;
	//prints out array of transactions
        transactionDisplay.innerHTML += ("<br>Transaction #" + index + " Date: " + id.date +   " Description: "
            + id.description + "<br> Type: " + id.type + " Amount: $"
            + id.amount.toFixed(2) + "<br>");
    }
}

Initially I relied on "values" from a locally accessible array, but now seek to extract such details from the JSON file. Any suggestions on how I can achieve this?

Answer №1

Some observations:

  • If you are diving into Ajax now, consider using the fetch API instead of XMLHttpRequest. Since you are already familiar with jQuery, you could also explore the $.getJSON function.
  • The Transactions class has a constructor meant for individual transactions, while the getTransactions method handles multiple transactions. It might be beneficial to separate these concepts and focus the class on managing one transaction only, along with a method that generates the HTML representation of a single transaction.
  • The variable values is not explicitly declared. Refactoring the previous point should provide all necessary properties within the class instance.
  • Given your use of jQuery, if "transactionDisplay" corresponds to an HTML element's id, remember to prepend the selector with a hash symbol:
    $("#transactionDisplay")
  • Since jQuery is in play, consider utilizing the ready event handler by simply binding it like so: $(function () { .... }.

Below is how I would rewrite the code:

$(async function () {
    const response = await fetch("../titan-bank/db.json");
    const obj = await response.json();
    const transactions = obj.transactions.map(({date, description, type, amount}, i) => 
        new Transaction(i + 1, date, description, type, amount)
    );
    $("#transactionDisplay").html(transactions.map(transaction => transaction.html()).join("<br><br>"));
});

class Transaction { // Each instance represents one transaction
    constructor (id, date, description, type, amount) {
        this.id = id; // defining here!
        this.date = date;
        this.description = description;
        this.type = type;
        this.amount = amount;
    }
    html() {
        return "Transaction #" + this.id
            + "&emsp;Date: " + this.date 
            + "&emsp;Description: " + this.description
            + "<br>&emsp;Type: " + this.type 
            + "&emsp;Amount: $" + this.amount.toFixed(2);
    }
}

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

merging JavaScript objects with complex conditions

I am attempting to combine data from two http requests into a single object based on specific conditions. Take a look at the following objects: vehicles: [ { vId: 1, color: 'green', passengers: [ { name: 'Joe', ag ...

Issue encountered in Flutter: jsonData condition failing as List<dynamic>

My current challenge involves retrieving data from a table called Collections in a local MySQL database. Below is the code snippet I am using: class CollectionsPage extends StatefulWidget { @override _CollectionsPageState createState() => _Collectio ...

javascript the debate between inline and traditional registration

Hey there, I'm a JavaScript beginner and currently learning about inline vs. traditional registration. I've managed to get code block 1 (inline) working perfectly fine, but unfortunately, code block 2 (traditional) isn't cooperating. Can som ...

Creating a structure object in a Laravel controller for implementing Vue.js autocomplete functionality

I am currently facing an issue with my autocomplete feature not displaying options correctly. To start off, I am fetching hard coded data from my controller and passing it through an axios call: searchController.php $searchResults = [ 0 => (ob ...

Refresh a table using jQuery Mobile, PHP, and AJAX without having to reload the entire page by clicking a

Currently, I am working on a web app that includes a pop-up feature. When the user clicks on the pop-up to close it, I want the table data to refresh without having to reload the entire page. This pop-up allows users to modify existing data in the table. A ...

Updating HTML in Vue.js with data at a specific index value can be done by targeting

Experimenting with a combination of vue.js and vanilla to create a blackjack game. The card data is stored in the vue data() like this: data(){ return { cards: [ {id: 1, cardName: 'Ace of Spades', cardPic: ' ...

"Exploring the world of Highcharts: A guide to loading data using

I am experiencing an issue with my application where highchart is not loading data via ajax. I have checked a demo provided on the highcharts website for loading highcharts via ajax, but it also seems to be not working. You can find the demo at this URL: h ...

Track user engagement across multiple platforms

Looking for solutions to log system-wide user activity in my Electron app. I want to track mouse-clicks and keystrokes to determine if the user is inactive for a certain period of time, triggering a timer reset within the application. I believe I may nee ...

Is there a jQuery AJAX method that can be invoked during the waiting process for error, success, or completion?

As I was about to use an ajax function and looking through the API, a question popped into my head. Is there a way to execute a function while waiting for the success, error, done, etc. callbacks to be triggered? I wondered if there could be something lik ...

NodeJS rendering method for HTML pages

We are in the process of developing a fully functional social networking website that will resemble popular platforms like Facebook or Instagram. Our plan is to utilize Node.js on the server side and we are currently exploring the best technology for rende ...

The error message "window is not defined" is commonly encountered in Next

Having some trouble with using apexcharts in a next.js application, as it's giving me an error saying 'window is not defined'. If anyone has any insights or solutions, I would greatly appreciate the help. Any ideas on what could be causing ...

Unexpected Issues with Page Refresh in AngularJS

I am currently working on an Angular application using the MEAN stack. Here's a scenario: imagine you have an express route that queries the database and sends the results back in the response: app.get('/api', function(req, res){ Todo.f ...

Showing the value of a JavaScript variable within an HTML input field

Here is an interesting HTML structure that includes a list and input field: <li> <span>19</span> </li> <li> <span>20</span> </li> ...

Unable to establish a connection with the docker container

I have developed a server-api application. When running the app on my localhost, only two simple commands are needed to get it up and running: npm install npm start With just these commands, the app runs perfectly on port 3000. Now, I am trying to dock ...

Changing nested JSON into a flat dataframe in R

Here is the structure of my JSON: I am looking to convert it into a flat dataframe. res <- jsonlite::fromJSON(data, simplifyDataFrame=TRUE) or res <- jsonlite::fromJSON(data, flatten=TRUE) However, these methods give strange results. I have t ...

Tips for incorporating inline images with gatsby-image

Seeking Solution In my quest to query and showcase images with a maximum width of 350px, I am hoping to have them displayed inline-block for tablets and larger screens. Ideally, each image would sit next to one another and wrap if they exceed the parent d ...

Changing time format from ISO time to short time in JavaScript

I am working on an ajax call that retrieves a time in the format 16:06:59, and I need to convert it to 4:06 PM. var mydate = obj[0].time; The variable mydate contains 16:06:59, but when I try to use it with var date = new Date(), it returns today's ...

designing a modular socket.io framework in node.js

Suppose in a node.js application, we have an app.js file structured like this: var express = require('express') var app = express(); var server = http.createServer(app); ... module.exports = { app:app, server:server } Additionally, there ...

Cross-Origin Resource Sharing problem: "Preflight request response does not meet access control criteria"

I'm currently tackling a Vue.js/Nuxt.js project that involves sending API requests to 'https://app.arianlist.com'. However, I've encountered some CORS challenges and came across this error message: "Access to XMLHttpRequest at &ap ...

Troubleshooting issue with Django forms and JavaScript interactions

For the past day, I've been grappling with a particular issue and haven't made much progress. My setup involves using a django inline form-set, which displays all previously saved forms along with an additional empty form. To show or hide these f ...