Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
Retrieve JSON from Ajax application and iterate JSON values in another function

Just starting out with Ajax but I am having a bit of an issue understanding if this is even possible. I have a db.json file that I am retrieving with 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 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();

Immediately after, the JSON file should be sent over to the this class that will then should iterate through the JSON file and output the 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 + "&emsp;Date: " + id.date +   "&emsp;Description: "
            + id.description + "<br>&emsp;Type: " + id.type + "&emsp;Amount: $"
            + id.amount.toFixed(2) + "<br>");
    }
}

Initially I was using "values" from locally available array, but now need to get this information from the JSON file. Any hints as to what I can do here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Some remarks:

  • If you start with Ajax now, then don't use the XMLHttpRequest API, but the fetch API. And as you seem to use jQuery, you could even use the $.getJSON function.
  • The class Transactions has a constructor that takes the properties of one transaction, while the getTransactions method is designed to deal with multiple transactions. So your class is mixing up the concept of one transaction and a set of multiple transactions. I would suggest dedicating the class to one transaction only, including a method that returns the HTML rendering of one transaction.
  • The values variable is not defined. With the change proposed in the previous point, you'd have all you need in the instance properties.
  • It seems you use jQuery. If "transactionDisplay" is the id of an HTML element then the selector should have a hash symbol: $("#transactionDisplay")
  • As you use jQuery, why not use the ready event handler which you can bind by just doing $(function () { .... }.

Here is how I would code it:

$(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 { // One instance is one transaction
    constructor (id, date, description, type, amount) {
        this.id = id; // let's define it 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);
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda