Roomka
Roomka

Reputation: 15

JQuery .ajax data not defined

I have a $.ajax request, and when i send response data with success:function(data), I get the data but for some reason I can't use it in If Statement:

    $.ajax({
      type: "POST",
      url: "control.php",
      data: {"txtNumFattura" : $("#txtNumFattura").val(),
             "txtDataFattura": $("#txtDataFattura").val()},

      success: function(data) {
        console.log(data);
        if (data == 'OK') {
          console.log("Chiave non ancora utilizzata");
          $("#submitMyForm").removeAttr("disabled");
        } 
        else if(data == 'KO') {
          $("#mySubmitForm").attr("disabled","disabled");
          console.log("Chiave Utilizzata");
        };
      }
    });

For instance console.log gives me "OK" or "KO" but it seems like it doesn't read it in the if Statement.

Upvotes: 0

Views: 1412

Answers (3)

Learner
Learner

Reputation: 4004

If you are sure that it gives you OK or KO, you can try this:

if ($.trim(data) === 'OK') {
  console.log("Chiave non ancora utilizzata");
  $("#submitMyForm").removeAttr("disabled");
} else if($.trim(data) === 'KO') {
  $("#mySubmitForm").attr("disabled","disabled");
  console.log("Chiave Utilizzata");
};

Upvotes: 0

Devin Crossman
Devin Crossman

Reputation: 7592

Try

if(data.toLowerCase().indexOf('ok') != -1){
  // ok was found
} else if (data.toLowerCase().indexOf('ko') != -1) {
  // ko was found
} else {
  // neither was found
}

Upvotes: 1

Andy G
Andy G

Reputation: 19367

There might be extra whitespace after the OK or KO. Use

console.log("*" + data + "*");

If there is you could use replace() to remove these. For example,

data = data.replace(/\s/g, "");

\s is a whitespace character and 'g' means globally.

Upvotes: 0

Related Questions