Xtreme Xtreme - 1 year ago 70
Ajax Question

If statement not working inside ajax success

I have this html code

<div class="vote">
<div data-post-id="@item.PostId" data-vote-rank="1" class="vote-arrow vote-up glyphicon glyphicon-chevron-up"></div>
<div class="total-vote">0</div>
<div data-post-id="@item.PostId" data-vote-rank="-1" class="vote-arrow vote-down glyphicon glyphicon-chevron-down"></div>

And this jQuery ajax post

$(".vote-arrow").click(function () {
var postId = $(this).data("post-id");
var voteRank = $(this).data("vote-rank");

type: "GET",
url: "/Posts/Vote/",
data: { postId: postId, voteRank: voteRank },
context: this,
success: function () {
console.log(voteRank); //working, I get 1
if (voteRank === "1") {
console.log(voteRank); //nothing in the console
$(this).css({ 'color': 'red' });

If-statement in the
is not working.

If I press the div with
I get 1 in the console from the
outside the if-statement and the
after the if-statement. voteRank in the if-statement condition is one if I debug but I don't get the console.log inside the if-statement (and of course not color change).

What is wrong?

Answer Source

Either use == or voteRank === 1, the identity (===) operator also check type, they must match to be considered equal.

The .data() internally convert value in to appropriate data-type. They are not string. 1 === "1" will evaluate to false

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download