0

How to get success ajax response value/string and use it on the if condition?

php will echo "valid" if success, else it will echo "invalid".

$("#submit-login").click(function () {

    var email = $('#mailInput2').val();
    var pass = $('#passInput2').val();

    $.ajax({
        url: 'func_login.php',
        data: 'login_email='+email+'&login_password='+pass,
        type: 'POST',
        success: function(data) {
           alert(data); //alert show 'valid'
           $('#test').html(data); //working, #test show 'valid'
           if(data == "valid"){
                $('#test').html(data); //not working when this inside 'if'
           }
           //I also tried
           //if(data['valid']){}
           //if(data === "valid"){}
           //if(data == 'valid'){}
           //if(data.content == 'valid'){}
        },
        error: function(xhr, textStatus, error){
          console.log(xhr.statusText);
          console.log(textStatus);
          console.log(error);
      }

     });
});
2
  • Please add dataType : "text" and try again. Commented Dec 21, 2018 at 16:40
  • still doesn't work, but I will keep that.
    – Lester
    Commented Dec 21, 2018 at 16:43

1 Answer 1

3

Try:

if(data.trim() == "valid"){
    $('#test').html(data);
}

data probably has some whitespace or newlines in the string so get rid of those.


Additionally, your comment says //alert show 'valid' so if single quotes are literally part of the string then you need:

if(data.trim() == "'valid'"){

In the future you can:

alert(data.length);

and if the length is not 5 then you know something is wrong.

2
  • Thanks, data.trim() fixed the issue!
    – Lester
    Commented Dec 21, 2018 at 16:51
  • 1
    @Lester Nice. See my update about detecting this issue in the future.
    – MonkeyZeus
    Commented Dec 21, 2018 at 16:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.