Here is my ajax call:
var totalCost = 0;
function GetTotalCost(start, end, rID)
{
$.ajax({
url: '@Url.Action("CalculateTotalcost")',
type: 'POST',
data: JSON.stringify({ start:start, end:end, rID:rID}),
dataType: 'json',
processdata: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { totalCost = data; }
// error: function (xhr, ajaxOptions, thrownError) { $('.datepicker1').datepicker("hide"); },
// complete: function (x, y) { $('.datepicker1').datepicker("refresh"); }
});
}
Here is my function from which I call ajax:
$('.datepicker2').datepicker({
dateFormat: 'dd/mm/yy',
firstDay: 1,
yearRange: '2012:2100',
beforeShowDay: function (date) {
var day = date.getDate();
if (day in alreadyTakenDays) {
return [false, '', alreadyTakenDays[day]];
}
else return [true, 'IsActive'];
},
onChangeMonthYear: function (year, month, inst) {
alreadyTakenDays = {};
getEvents(month, year);
},
onSelect: function (dateText, inst) {
var end = dateText.substring(0, 2);
console.log(end);
var rID = $('#RoomID').val();
console.log(rID);
var startingHole = $('#DateOne').val();
var start = startingHole.substring(0, 2);
console.log(start);
GetTotalCost(start, end, rID);
document.getElementById('TotalCost').value = totalCost.toFixed(2);
}
});
After jQuery script is executed I always get 0 for totalCount?
Why is this happening? What should I Do?
I would like to appoint totalCount to Html.TextBoxFor in ASP.NET MVC 3, that is why I need totalCount. Please help.
You should have success function handler like this to get correct total cost value:
In code like this:
First line cause ajax call, but it does not wait for response and second line is executed immediately. Later, after server responded,
successcallback function is executed. And it will be executed after second line. That is why your total value is wrong – correct value is set tototalCostafter you update TotalCost input.