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
Declare totalAmountAccrued and amountWrittenOff with let above the ajax call.
like let totalAmountAccrued;
Remove const from
const totalAmountAccrued
andconst amountWrittenOff
.You can use $.when to combine multiple requests
https://api.jquery.com/jquery.when/
Use
Promise.all
which triggersthen
when all promises are resolved