synan54
synan54

Reputation: 658

if statement mistake on jquery

hi there i am working on a jquery ajax solution for my webpage there is a getir.php i use it for jquery post data (it is a username) and if name exist it echo 'TRUE' or 'FALSE'

here it is

if (isset($_POST['name'])) {
if($synan->checkNameIsExist($_POST['name'])){
    echo'TRUE';
}else{
    echo'FALSE';
}
}

it works fine i see true or false results in console but i have problems on jquery part

$(document).ready(function () {
    $("#user_name_reg").blur(function () {
        txt = $(this).val();

        $.post("getir.php", {
            name: txt,
            method: "checkName"
        }, function (result) {

            console.log(result);
            if (result == 'TRUE') {
                $("span").html("answer true");
            } else {
                $("span").html("answer false");
            }
        });
    });
});

i couldnot make it work the if statement . thank you for your suggestions

Upvotes: 0

Views: 88

Answers (2)

hek2mgl
hek2mgl

Reputation: 157947

If PHP is using the default content type: 'text/plain' and is really returning just either 'TRUE' or 'FALSE' without any leading whitespaces or other content surrounding it the example above will work. You should make this sure using quotes around the output when calling console.log(). Like this:

console.log("'" . result . "'");

If there are whitespaces around it, make sure that you have no content before the opening <?php tag or after the closing ?> tag in PHP

Upvotes: 1

jmar777
jmar777

Reputation: 39649

Given that your output from:

console.log(typeof result, result.length, result);

was string 78 true, we know 3 things:

  1. We're dealing with a string
  2. There's a lot of whitespace involved
  3. There's some weird case conversion going on.

The solution below accounts for these observations:

result = $.trim(result).toLowerCase();
if (result == 'true') {
    $("span").html("answer true");
} else {
    $("span").html("answer false");
}

Upvotes: 3

Related Questions