JQuery, AJAX, comparing returned JSON value

45 Views Asked by At

What am I doing wrong here? The grey class is removed for the first conditional (===5) but is not removed with the other conditional statements?

Thanks for looking at it,

Javascript:

 function getTrophy() {
  $.ajax({
   url: "ajax/ajax_dashboard.php?f=14",
   type: "GET",
   success: function(data) {
    var json;
    json = $.parseJSON(data);
    if(parseInt(json.volunteer[0])===5) {
     $("#volunteer-trophy").removeClass("grey");
    }    
    if(parseInt(json.mindful[0])>=5) {
     $("#mindful-trophy1").removeClass("grey");
    }    
    if(parseInt(json.mindful[0])>=10) {
     $("#mindful-trophy2").removeClass("grey");
    }
    if(parseInt(json.mindful[0])>=15) {
     $("#mindful-trophy3").removeClass("grey");
    }
    if(parseInt(json.mindful[0])>=20) {
     $("#mindful-trophy4").removeClass("grey");
    }
      }
    })
  }

JSON

​{"volunteer" : "5", "mindful" : "10"}
1

There are 1 best solutions below

8
NaijaProgrammer On BEST ANSWER

To achieve the intended result, so your code should be like this:

            if(parseInt(json.volunteer)===5) {
                $("#volunteer-trophy").removeClass("grey");
            }               
            if(parseInt(json.mindful)>=5) {
                $("#mindful-trophy1").removeClass("grey");
            }               

Better still, to avoid errors, you should store the volunteer and mindful in variables:

            var volunteer = parseInt(json.volunteer);
            var mindful   = parseInt(json.mindful);
            if( volunteer === 5) {
                $("#volunteer-trophy").removeClass("grey");
            }               
            if( mindful >= 5) {
                $("#mindful-trophy1").removeClass("grey");
            }               

UPDATE: As pointed out by @charlietfl, the last 3 conditions are redundant, since the test for mindful > 5 fulfills the condition for the three conditions after it.