0

Same variable (119), same constant (100). Both are correctly interpreted as numbers when using the subtraction and multiplication operators, however not so when using the addition operator - the result is a string (119100). However when I apply the parseFloat function with the addition operator I get the correct result (219). Does Jquery interpret the '+' operator as a string concatenator?

var newvotes = 0;

$(document).ready(function(e) {

//alert(1);


$('.vote').children().click(function(e) {
e.preventDefault(e);
var vote = $(this).text();
var timestamp = 1369705456;

$.ajax({
type: 'POST',
url: 'forumvote.php',
data: {'timestamp' : timestamp, 'vote': vote},
success: function(data, textStatus) {
  newvotes = data;

 },

//dataType: 'text',
async:false,
});

alert(newvotes); //119
var newvar = newvotes*100; 
var newvar2 = newvotes-100; 
var newvar3 = newvotes+100;
var newvar4 = parseFloat(newvotes) + parseFloat(100); 
alert(newvar); //11900 ok
alert(newvar2); //19 ok
alert(newvar3); //119100 returns as a string
alert(newvar4); //219 ok

})

1 Answer 1

1

Its not jQueries fault. Its just what Javascript does.

If you look at the type of newVotes you'll find its a string. ( typeof(newVotes) ). The binary operators * and - convert their arguments to numbers. The binary operator + if either argument is a string converts the other arguments to strings. Otherwise it converts them to numbers.

So all you need to do is convert your data to a number in your success callback and all will work for you:

$.ajax({
type: 'POST',
url: 'forumvote.php',
data: {'timestamp' : timestamp, 'vote': vote},
success: function(data, textStatus) {
  newvotes = parseFloat(data);

 },

//dataType: 'text',
async:false,
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Good solid answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.