6

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);');
  }
 });
}
Brad
  • 5,845
  • 7
  • 30
  • 29

3 Answers3

17

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
  • 349,597
  • 67
  • 533
  • 578
  • 2
    +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. – Dexygen Jun 22 '09 at 23:10
  • 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 Dec 26 '09 at 07:04
6

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.

cgp
  • 41,026
  • 12
  • 101
  • 131
  • One clue I found when investigating a problem like this was doing a view source in the browser and seeing a blank line prior to the DOCTYPE declaration (first line in the web page). – Scott C Wilson Dec 06 '12 at 12:09
  • This. I just removed the ?> from the end of my CodeIgniter model php file and it fixed the problem, no more whitespace output! – skiindude22 Apr 24 '14 at 18:44
5

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
  • 2,042
  • 14
  • 23