skip to Main Content

I want to add two numbers and calculate the total from two different ajax calls, so that I can append the total value to a dom

 $.ajax({
            url: "@Url.Action("MonthlyReport")",
            data: { id: id },
              success: function (data) {
                  var total = 0;
                  for (var i = 0; i < data.length; i++) {


             // Create our number formatter.
                total += data[i].interestAmountPerMonth 

               }

                  var formatter = new Intl.NumberFormat('en-US', {
                      style: 'currency',
                      currency: 'USD',
                  });

                  const totalAmountAccrued = formatter.format(total)
                  $('#totalAmountAccrued').append(totalAmountAccrued)

            },
            error: function (req, status, error) {}
          });

The second ajax is below

     $.ajax({
            url: "@Url.Action("GetAllLoan")",
            data: { id: id },
            success: function (result) {

                var formatter = new Intl.NumberFormat('en-US', {
                    style: 'currency',
                    currency: 'USD',
                });

                const originalLoanAmount = formatter.format(result.originalLoanAmount);
                const amountWrittenOff = formatter.format(result.amountWrittenOff);
                

            },
            error: function (req, status, error) {
            }
        });

I want to achieve something like this let overallTotal = totalAmountAccrued + amountWrittenOff

3

Answers


  1. Declare totalAmountAccrued and amountWrittenOff with let above the ajax call.

    like let totalAmountAccrued;

    Remove const from const totalAmountAccrued and const amountWrittenOff.

    Login or Signup to reply.
  2. You can use $.when to combine multiple requests
    https://api.jquery.com/jquery.when/

    Login or Signup to reply.
  3. Use Promise.all which triggers then when all promises are resolved

    function makeFetch(url, data) {
        return $.ajax({url: url, data: data})
    }
    
    Promise.all([
        makeFetch('@Url.Action("MonthlyReport")', {id: id}),
        makeFetch('@Url.Action("GetAllLoan")', {id: id})
    ])
    .then(([monthlyReport, allLoan]) => {
        const totalAmountAccrued = monthlyReport.reduce((sum, data) => sum + data.interestAmountPerMonth, 0)
        const amountWrittenOff = allLoan.amountWrittenOff
        const overallTotal = totalAmountAccrued + amountWrittenOff
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search