tags:

views:

360

answers:

3

I'm using jQuery to make ajax requests. The data is getting to PHP nicely, but the response isn't getting back to javascript properly. Somehow there is a space before the response. I know this because Firebug says so and my code doesn't work because the space is there. When I expect there to be a space it works fine. Any ideas as to what could be adding the space?

Here is my ajax function:

function my_ajax (aurl, adata, aretfunc) {
 $.ajax({
  type: "POST",
  url: aurl,
  data: adata,
  success: function(msg) {
    eval(aretfunc+'(msg);');
  }
 });
}
+3  A: 

Look for spurious whitespace characters outside of the <?php ?> tags in your PHP file. Any such whitespace will get output when the PHP script is executed. If your PHP file includes other PHP files, the same thing applies to those files as well.

John Kugelman
+1 this can be one of the most insidious bugs. I encountered this when working on some PHP code along with a 3rd party vendor. On one iteration, without testing, they decided to add a block of comments at the top of every file within its own PHP block, followed by an empty line before the actual PHP code block. Well that blank line was considered content sent to the browser, so any/all code that subsequently needed to set http headers (for example) failed miserably.
George Jempty
Hi... The same is happening to my code now.. i've tried removing any unnecessary space without affecting the readability of the code... still i get the spaces...Anyway.. i've used spaces in my earlier codes quite liberally but only now i see this problem....
SpikETidE
+1  A: 

Agreed, look for spurious whitespace character outside of the <?php ?>. One suggestion, and one that is completely legit is to simply remove the trailing ?>, as they are unnecessary. In fact, it's a coding standard for Drupal.

altCognito
A: 

In some cases, I've found that just running the response through $.trim() before doing anything can work fairly well.

Of course, the solutions above are still very applicable, but if you're in a situation where you can't change that, I figured it'd be worth throwing out there.

Ryan McGrath