how can i save Transactions and get the Transactions back when i reload my page?

28 Views Asked by At

in this code i want to save the Transactions and get the Transactions back when i reload my page so that the records will stay there forever. but it seems its not working that way. i dont want to do any server side work. i want all the code on one same page. anyone who want to help me . have to fix the full code for me cuz i am new to this.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Money Transfer System</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="profile" id="user1">
    <h2>User 1</h2>
    <p>Balance: $<span class="balance">100</span></p>
    <input type="number" class="amount" placeholder="Enter amount">
    <input type="text" class="receiver" placeholder="Receiver username">
    <button onclick="sendAmount(1)">Send Money</button>
    <h3>Transaction Records</h3>
    <ul class="transactionRecords"></ul>
  </div>

  <div class="profile" id="user2">
    <h2>User 2</h2>
    <p>Balance: $<span class="balance">150</span></p>
    <input type="number" class="amount" placeholder="Enter amount">
    <input type="text" class="receiver" placeholder="Receiver username">
    <button onclick="sendAmount(2)">Send Money</button>
    <h3>Transaction Records</h3>
    <ul class="transactionRecords"></ul>
  </div>


  <script>
      function sendAmount(sender) {
  let parentProfile = document.getElementById('user' + sender);
  let amount = parseFloat(parentProfile.getElementsByClassName('amount')[0].value);
  let receiver = parentProfile.getElementsByClassName('receiver')[0].value;
  let balanceElement = parentProfile.getElementsByClassName('balance')[0];
  let balance = parseFloat(balanceElement.textContent);

  if (receiver !== "user" + sender) { // Prevent sending to oneself
    if (amount > 0 && amount <= balance) {
      // Validate the receiver's username
      if (receiver === "user1" || receiver === "user2") {
        // Deduct the amount from sender's balance
        balance -= amount;
        balanceElement.textContent = balance;

        // Update sent records for the sender with date and time
        let sentRecords = parentProfile.getElementsByClassName('transactionRecords')[0];
        let sentRecord = document.createElement('li');
        let currentDate = new Date().toLocaleString(); // Get the current date and time
        sentRecord.textContent = `Sent $${amount} to ${receiver} - ${currentDate}`;
        sentRecords.appendChild(sentRecord);

        // Update received records for the receiver with date and time
        let receiverProfile = document.getElementById('user' + (receiver === "user1" ? 1 : 2));
        let receiverBalanceElement = receiverProfile.getElementsByClassName('balance')[0];
        let receiverBalance = parseFloat(receiverBalanceElement.textContent);
        receiverBalance += amount;
        receiverBalanceElement.textContent = receiverBalance;

        let receivedRecords = receiverProfile.getElementsByClassName('transactionRecords')[0];
        let receivedRecord = document.createElement('li');
        receivedRecord.textContent = `Received $${amount} from User ${sender} - ${currentDate}`;
        receivedRecords.appendChild(receivedRecord);
      } else {
        alert("Invalid receiver username. Please enter 'user1' or 'user2'.");
      }
    } else {
      alert("Invalid amount or insufficient balance");
    }
  } else {
    alert("You cannot send money to yourself.");
  }


   // After updating the transaction records, save the transaction to transaction.txt
      saveTransactionToTxt(sentRecord.textContent); // save the transaction details to file
    }

    function retrieveTransactions() {
      fetch('transaction.txt')
        .then(response => response.text())
        .then(data => {
          // Parse the data and populate transaction records
          // Example:
          // let transactionRecords = data.split('\n');
          // transactionRecords.forEach(record => {
          //   // Populate transaction records in the respective user profiles
          // });
        })
    }

    function saveTransactionToTxt(transactionDetails) {
      fetch('saveTransaction.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ transaction: transactionDetails })
      })
      .then(response => {
        if (response.ok) {
          // Transaction details saved successfully
        } else {
          // Handle error
        }
      })
      .catch(error => {
        // Handle error
      });
    }

    // Call retrieveTransactions when the page loads to populate transaction records
    window.onload = retrieveTransactions;
  </script>
</body>
</html>
1

There are 1 best solutions below

0
Suryateja KONDLA On
<script>
  function sendAmount(sender) {
     // After updating the transaction records, save the transaction to localStorage
    saveTransactionToLocalStorage(sender, sentRecord.textContent);
    saveTransactionToLocalStorage(receiver === "user1" ? 2 : 1, receivedRecord.textContent);
  }

  function saveTransactionToLocalStorage(user, transactionDetails) {
    let transactions = localStorage.getItem('transactions_user' + user);
    transactions = transactions ? JSON.parse(transactions) : [];
    transactions.push(transactionDetails);
    localStorage.setItem('transactions_user' + user, JSON.stringify(transactions));
  }

  function loadTransactions() {
    for (let user = 1; user <= 2; user++) {
      let transactions = localStorage.getItem('transactions_user' + user);
      if (transactions) {
        transactions = JSON.parse(transactions);
        let transactionList = document.getElementById('user' + user).getElementsByClassName('transactionRecords')[0];
        transactions.forEach(transaction => {
          let listItem = document.createElement('li');
          listItem.textContent = transaction;
          transactionList.appendChild(listItem);
        });
      }
    }
  }

  // Call loadTransactions when the page loads to populate transaction records
  window.onload = loadTransactions;
</script>

saveTransactionToLocalStorage function saves each transaction in localStorage. It keeps an array of transactions for each user.

loadTransactions function is called when the page loads. It retrieves the stored transactions from localStorage and populates the transaction records for each user.