php - if statement mistake on jquery

271

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

894

Answer

Solution:

Given that your output from:

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

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

Answer

Solution:

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 callingconsole.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

People are also looking for solutions to the problem: php - Capturing multiple value from dropdown list generated from database

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.