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

Tips for preserving checkbox state?

I am currently working on a web application project for a clinic and laboratory, specifically focusing on sending tests. I have implemented the code below to select the test category first, followed by the test name related to that category. However, when ...

`The resurgence of CERT_FindUserCertByUsage function in JavaScript`

I am currently grappling with unraveling the connection between C++ dlls and JavaScript. There is a snippet of js code that reads: cert = CERT_FindUserCertByUsage(certDB, certName.nickname,certUsageEmailSigner, true, null); where the variable cert is ini ...

Exploring the location.path in angularjs

Is there a way to use $location.path for redirection in angularjs? I have the configuration below: ngModule.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $urlRouterProvider. ...

How to format time in Node.js using PostgreSQL

I have set up two tables in my Postgres database, one called users and the other called card_info. I have implemented an endpoint for new user registration, and I have included a field named dateCreated in the code snippet below. Register.js const handle ...

"ASP.NET MVC issue: Ajax request is returning a view instead of the expected ajax

I have a situation where an ASP.NET MVC call to a method via AJAX is throwing an exception error. I want the exception message to be sent back to the client without having to catch the exception explicitly. Here's what I'm trying to achieve: [Ht ...

Manipulating object information within a nested for loop

I have a variable called jobs in my scope, which is an array containing objects for each department along with their respective data. [ “Accounting”: { “foo” : “foo”, “bar” : "bar" }, “Delivery”: { ...

Implementing server-side validation measures to block unauthorized POST requests

In my web application using angular and node.js, I am in the process of incorporating a gamification feature where users earn points for various actions such as answering questions or watching videos. Currently, the method involves sending a post request t ...

Create node panels using GoJS and apply paint to them to enhance

Hey there! I'm looking to style my node similar to the one on the right using GOjs. Any suggestions on how I can achieve that? The left node is what I currently have, but I really want to paint it like the right node. It seems like some parts are mi ...

When pasting Arabic text into an input box, the words in HTML appear to be jumbled and shuffled around

When I replicate this text يف عام and input it into a box, the output is shown as follows عام يف ...

Exploring the use of jQuery's .filter() method to showcase JSON data

I am currently working on a webpage that includes images, details, and a search input option using JSON objects. The issue I'm facing is that the search function does not yield any results, even though the data from the JSON object displays correctly ...

It is not possible to alter or manipulate dynamic content received from an Ajax/JSON response when creating a dynamic PHP form

I am in need of a dynamic form that functions as follows: Upon clicking the "ADD" button, a new <div> element should appear for selecting a package. Based on the selected package, the row should change its color by adding or removing certain classe ...

Using node.js to iterate through unspecified objects

I am facing the challenge of working with a directory of files generated by a service, where each file lacks an extension. Here are some examples of file names: all_events_20170406v1 all_events_20170406v2 These files contain multiple JSON objects without ...

Issues with passing parameters in JavaScript

I am facing an issue while passing multiple variables from a PHP page to a JavaScript function. Only the first parameter seems to be passed successfully. In the PHP code, the script is being called like this: <? $sdate = 0; $edate = 2; ?> <scrip ...

Monitoring the usage of a specific component's screen time in a React Application

Is it possible to accurately track the time a specific component is rendered with certain props and while being on an active screen in React? I've had trouble finding a suitable library for this task. What would be the most effective approach to tackl ...

Instead of pushing multiple items, focus on pushing only one item at a time

I've encountered an issue while attempting to add a new item to my favlist. Using a for loop, I check if the item already exists in the favlist. However, instead of adding the new item only once, it ends up being added multiple times. What would be ...

Is there a way to disable automatic spacing in VS code for a React file?

I am currently working on my code in VS Code within my JSX file, but I keep encountering an error. The issue seems to be that the closing tag < /h1> is not being recognized. I have attempted multiple methods to prevent this automatic spacing, but so ...

Provide a boolean value of true or false to indicate whether all delete operations were successfully completed

Currently, I am using Sequelize, GraphQL, and Typescript for my coding. Within my database, I have two tables named RecordInformation and OtherDescription. The RecordInformation table contains a foreign key called "OtherID" which references the OtherDescri ...

Transmission of data between tabs within an AJAX tab container in ASP.net

In my ASP.net application, I have implemented tabpanels on a page. When a user clicks the submit button while on the first tab, the second tab control is displayed. Ontabindexchanged event, I am dynamically generating a usercontrol and passing values to it ...

I am interested in creating a space where I can gather all the paths for each folder

Here is my code snippet: folder_out = [] for a in range(1,80): folder_letter = "/content/drive/MyDrive/project/Dataset/data/" folder_out[a] = os.path.join(folder_letter, str(a)) folder_out.append(folder_out[a]) However, an error occ ...

Tips for modifying string in key-value pairs on the client side (example using Paypal checkout demo)

Looking to integrate an online payment system into my small online business, I have decided on using PayPal. Their solution is user-friendly and can be found here: https://developer.paypal.com/demo/checkout/#/pattern/client However, I am facing an issue w ...