0

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.

2
  • what data are you expecting in response? Commented Jul 4, 2013 at 20:17
  • It just gives in response "OK" if the value inserted is not already used as a Primary Key in my table. Commented Jul 4, 2013 at 20:33

3 Answers 3

1

Try

if(data.toLowerCase().indexOf('ok') != -1){
  // ok was found
} else if (data.toLowerCase().indexOf('ko') != -1) {
  // ko was found
} else {
  // neither was found
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Devin, It helped! Can you explain me please why it didn't work before?!
using indexOf will search the whole string for any occurrence of ok or ko whether there is any whitespace or any other characters.. using toLowerCase() is just to make sure that no matter how you typed it Ok, OK, oK, ok it will find it.
0

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.

Comments

0

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");
};

1 Comment

Actually this works too! Don't know why, But for some reason it put an extra whitespace.

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.