I just had to fix an AJAX failure in the admin area (the search/attach dialog box in the Media Library wasn't working) and tracked down a plugin that was the culprit.

On activation, this plugin was generating 'unexpected output' (it had a space after the final php tag).

Removing this solved the problem. Why was it causing it in the first place?

  • What Plugin, specifically? Oct 28 '11 at 12:31
  • A plugin I had made myself - happy to post code in a pastebin if you like?
    – djb
    Oct 28 '11 at 12:38
  • It might be relevant? I'm not sure, because I don't know the first thing about AJAX. I do know, however, that the headers already sent error can be a real bugger, especially when caused by errant whitespace after a closing ?> tag in functions.php. Oct 28 '11 at 12:40
  • I thought that was what it was... but i don't quite understand how that affects things, which is why I'm asking :). I'm fairly certain it's not the code itself, as I deactivated each of the hooks in turn, wrapped the whole thing in if(!is_admin) etc...
    – djb
    Oct 28 '11 at 12:42

The HTTP Protocol that runs both page loading, file downloading and AJAX functionality requires a headers (multiple lines) consisting of Name: Value and TWO ENTERS (separator) and then the actual data.

Headers are very important as they control what the browser should do with the received data and state what the data is. AJAX needs to send headers that specify the Content-Type of delivered data, even Content-Length. It can be TEXT/HTML/XML/JSON/JS... etc. Regardless, bad headers can lead to bad data decoding. Browsers should not guess what you're sending. They should know exactly based on what the headers advertise.

That's why AJAX requires sending some special headers. But headers can not be sent after output, of any kind. So, using the header() function in PHP generates errors if you do it after data was sent. It's PHP's attempt to tell you that special instructions you need to send to the browser before actual data are not delivered. This causes a chain reaction as the error output will break the XML/JSON consistency of delivered data. This, in turn, breaks the AJAX functionality as expected XML/JSON can not be decoded (it contains illegal structures generated by the errors generated by the premature output).

This is why it's very important that plugins don't start/end with spaces. If you have output problems, use the headers_sent() function and it will allow you to discover where output has started and fix the offending code.

I'm pretty sure I made no sense, but Web Developers should understand the underlying protocols that power the web. Not low-levels like TCP-IP/ICMP... but higher-level like HTTP... We work at this level!



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.