RobinHo
RobinHo

Reputation: 575

comparing strings in javascript (string origin is from xmlhttp.responseText)

My servlet responds a string which contains "false" or "true" => Servlet code: out.println(validusername); validusername is a string from my servlet that goes to the var validusername in my javascript.

so in my front-end, I have this javascript code: The problem is that when my servlet returns false, the javascript always jumps into the "else".. I am wondering why.. searching this for hours. I know that my servlet responds with a "false" because the alert(validusername) occurs a popup window with the text "false" in it... Do you guys have any idea why validusername =="false" always jumps in my else tag?

I think there is something wrong with the comparision, but I can't find it...

Thank you so much for helping

var validusername = xmlhttp.responseText; 
 if (validusername == "false") {

  alert("username already exists");
 }
 else {

 alert("username free");
 alert(validusername); //this popup contains the value "false"

Upvotes: 0

Views: 1091

Answers (2)

Stop using alert(...) as of today, and start using "console.log(...)" instead. It'll print the data to the web console, and you get much better insight in what's going on. It also doesn't block your page. Without information on what's going on, the first advice is to force-validate all your data. Even if you own the servlet.

force if (validusername == "false") to resolve correctly by instead using if (validusername.trim() === "false") -- now if it fails, at least the string can't "look" like false without actuallying being "false".

Upvotes: 1

AllTooSir
AllTooSir

Reputation: 49402

Probably you need to trim the String and compare.

validusername = validusername.replace(/^\s+|\s+$/g,"");

Upvotes: 0

Related Questions