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
You can use $.when to combine multiple requests https://api.jquery.com/jquery.when/
Declare totalAmountAccrued and amountWrittenOff with let above the ajax call.
like let totalAmountAccrued;
Remove const from const totalAmountAccrued
and const amountWrittenOff
.
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
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.