Hello,

I have a problem with the response text of an ajax request.

I want to use the answer of the php script ("true" or "false") to do different things with a if-condition, but it always takes the false option.
Here is the code.

var hr = new XMLHttpRequest();
...
var data = hr.responseText;
document.getElementById("status").innerHTML = data + "  " + data.length + "    ";

if (data != "true"){
	document.getElementById("status").innerHTML = "yes";
} else {
	document.getElementById("status").innerHTML = "no";
}

When using the data.length method, it says the response text has 306 letters (!!).

Just for testing I simplified the php script to the following:

<?php
echo "true";

It's still 303 letters.

Where is the problem? Where do all the letters come from?

Thanks you for all :)

This

if (data != "true")

shoud be:

if (data == "true")

I know, put the wrong php code up to here, but it doesn't works with both.

when you print the data, what does it show?

Here's my full code:

function startlogin(one, two)	{
var hr = new XMLHttpRequest();
var url = /*myurl*/;
var fn = document.getElementById(one).value;
var ln = document.getElementById(two).value;
var vars = "startuser="+fn+"&startpassword="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = hr.responseText;
if (data != "true"){ // or false...
	document.getElementById("status").innerHTML = "yes";
} else {
	document.getElementById("status").innerHTML = "no";
}
}}
hr.send(vars);
document.getElementById("startloading2").style.display = "block";
}

The thing is the length of hr.responsetext! What do you think about that?

what do you mean? The length should be 4, isn't it?

And your code remains wrong: data != "true"

try alerting the data and see that it says:

alert(data);

Oh man, my hoster puts his analytics code there!
Any idea of removing this?

what do u mean? show me the result.

That's sucks... the best option is to disable this functionality on the pages you need.Talk to your host provider to know how you can do it.

But you gotta other options too, one of them is to ignore that text, use replace or something like that.

Replace is a good idea...

You can make something like this:

data = data.substring(data.lastIndexOf('-->') + 4);

Bad mistake. Thanks man.

No problem, u r welcome.

Just mark as solved please.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.