Avoiding the AJAX New Line Pitfall

Here, my friends, is a JavaScript pitfall that has plagued entire workdays. It's small and simple, but menacing ... you'd do well to heed this warning!

Beware of Trailing New Lines!

If you're retrieving information via AJAX, you have two easy options for retaining your sanity:
  • Make sure the document sending a response to your AJAX request has no trailing Newline. This includes all the files that may be included or required in a php file.
  • Sanitize the server response with a whitespace trim function
Why is that? Let's take a look at an example.

Example of the Pitfall

Let's execute a simple jQuery.post request to see how this can happen.
    <title>jQuery AJAX Pitfall</title>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

  <script type="text/javascript">
$.post("ajax.php", function(data) {
      alert(data == "foo")

Now we have a file ajax.php
echo "foo";
The file whitespacetrap.php is simply a file with a newline. (Just open up notepad and press enter once and save). You'll see "false" as the alert when you load up the html file. Now comment out the require file in ajax.php, and reload the html file. It's now true! That new line is concatenated with the echo and returned. This will completely screw up any string comparisons with the response message.

Moral of the Story

Use console.log or alert to echo print the value the server sends. If your string comparisons fail when you KNOW they shouldn't, make sure there are no stray newlines in the files associated with an AJAX request. August 31, 2011
About the Author:

Joseph is the lead developer of Vert Studios Follow Joseph on Twitter: @Joe_Query
Subscribe to the blog: RSS
Visit Joseph's site: joequery.me