0

I am trying to add a condition to some jquery script but for some reason I can't get it to work. I hope someone can tell me what I have got wrong. I want the script to show different text in a div depending on the value of a variable gotten through ajax. Many thanks.

The ajax bit of my script

$(document).ready(function() {

       //Fetch data from server

       $.ajax({
           url: 'my_data.php',
           dataType: "json",
           success: function(data) {

               $("#a").text(data.a);
               $("#b").text(data.b);

               var a = data.a;
               var b = data.b;


               //Condition
               if (a > b) {
                   $("#advice").text("a is greater than b");
               } else {
                   $("#advice").text("b is greater a.");
               }
           }

       });
3
  • try to alert(a+' > '+b) before condition statement and what is the result ? Commented Jun 5, 2016 at 17:03
  • @martiendt that would simply alert a concatenated string. Don't see how that would help Commented Jun 5, 2016 at 17:19
  • I get the alert with the variable values regardless of whether 'a' is greater than 'b' or 'b' greater than 'a'. Commented Jun 5, 2016 at 17:21

2 Answers 2

3

try parsing your variable to integer using parseInt(a)

$(document).ready(function() {

   //Fetch data from server

   $.ajax({
       url: 'my_data.php',
       dataType: "json",
       success: function(data) {

           $("#a").text(data.a);
           $("#b").text(data.b);

           var a = parseInt(data.a, 10);
           var b = parseInt(data.b, 10);


           //Condition
           if (a > b) {
               $("#advice").text("a is greater than b");
           } else {
               $("#advice").text("b is greater a.");
           }
       }

   });
Sign up to request clarification or add additional context in comments.

Comments

1

Depending on the data types of data.a and data.b you might get unexpected behaviour if they're not of the type number.

If data.a and data.b are strings, arrays or Object types, using relational operators will result in behaviour that might not be expected, for example:

console.log('19' > '109'); // false
console.log([1,2] > [2,3,4]); // false
console.log({} > {1: 2}); // false

You can convert strings to float using parseFloat(data.a) or int using parseInt(data.a, 10). The 10 is the radix.

To see what the types are of data.a and data.b are use the typeof keyword:

console.log(typeof data.a);
console.log(typeof data.b);

If these aren't Number, then convert them to float or int before using relational operators.

1 Comment

Thanks for this. They are numbers, I should have said.

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.