phpjavascriptajaxresponsetext

responseText contains extra whitespace characters (new lines, line feeds), how to prevent and remove them?


I have an ajax script that calls a php file.

The php file echos "yes" or "no", I want to use the strings to do logical comparisons.

In the javascript, I want to compare the string in the responseText to see if it is == to "yes" (or "no"). But the comparison fails.

So I do the alert responseText, and it does show "yes" (or "no") as the string. But I read on here that the responseText might contain hidden whitespace characters, so I did the string length of responseText and it shows that the string length is 4 characters longer than what it should be. So I escaped the responseText alert(escape(responseText)) and it shows that I have %0A and %0D (newlines and line feeds) hidden at the end of the responseText string.

I read that these characters are added on by php, but I also read that the extra characters are different among different php versions/servers.

How to prevent these extra whitespaces without using regex, since regex might remove intentional whitespaces?

Please don't suggest using jquery or mootools as answers.

TIA


Solution

  • I read that these characters are added on by php, but I also read that the extra characters are different among different php versions/servers.

    That's wrong. That's simple to verify: create a test.php file, write this and only this: <?php echo "test"; (without ?>) into it and execute it. There will be no whitespace.

    These whitespaces most probably come from your scripts. A common error is to leave some trailing newlines after a closing php tags (?>), which results in a new line being printed.

    Verify that all files included before or after you do echo "yes"; don't echo anything and don't have a trailing newline after a ?>.

    The easiest way to avoid this problem is do not use php close tags at end of files (they are not mandatory).