Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Space Before Ajax Response (jQuery, PHP)

Tags:

jquery

ajax

php

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);');
  }
 });
}
like image 486
Brad Avatar asked Jun 22 '09 22:06

Brad


3 Answers

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.

like image 83
John Kugelman Avatar answered Sep 20 '22 16:09

John Kugelman


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.

like image 27
cgp Avatar answered Sep 21 '22 16:09

cgp


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.

like image 44
Ryan McGrath Avatar answered Sep 23 '22 16:09

Ryan McGrath