Im trying to perform simple calculations using jQuery but I’m getting NaN as result.
Here is my javascript:
$(document).on('click','.button-group button:not(.done)', function(e){
e.preventDefault();
$(this).addClass('active');
var votevalue = $(this).data('votevalue');
var image_id = $('.mainimage').data('image_id');
var votes = $('.mainimage').data('numvotes');
var totalscore = $('.mainimage').data('totalscore');
$.ajax({
type: 'POST',
url: '?a=vote',
data: {
"votevalue" : votevalue,
"image_id" : image_id
},
success: function(){
var votes = parseInt(votes);
votes++;
var average = ((parseInt(totalscore) + parseInt(votevalue)) / votes);
$('#vote-incremenet').html(votes);
$('#display-average').html(average);
$('#display-average').show();
$('.button-group button').addClass('done');
}
}); // end ajax
}); // end click
What am I doing wrong?
When you use parseInt, be sure to pass
(parseInt(str), radix)to prevent an automatic conversion to some other base.(MDN)
In your case,
parseInt(varname, 10);If the issue persists, it is likely you are passing an incorrect value to one of the variables you are using for calculation.
EDIT:
var votes = parseInt(votes);inside the call-back makes it a local variable. Hence,it has lost the value it was given outside. Do not redeclare it within the callback.