Ajax Uploading Plus JSON Response Plus JSONView = Disaster

December 11, 2009

So, I’ve spend the last few hours debugging what seemed to be a tear in the fabric of the universe. I’m working this excellent javascript library, AjaxUpload, that, as the name implies, creates a no-pageload form upload. It’s easy to implement and makes an upload infinitely more usable in my opinion; definitely check it out.

The upload works by pointing the target attribute of a multipart form at a hidden iframe. When the iframe updates with the results of the upload, an event listener reports the response to the parent page, and voila — you have an upload without a page refresh.

The only problem with this iframe approach is that your response is being fully rendered by the browser instead of passed in the response body of an XMLHttpRequest like most ajax interactions. Combine this with a server-side upload script that returns JSON and here’s where the fun starts.

If you’re using the JSONView Firefox plugin (and why the hell aren’t you!?) the JSON gets rendered with some wrapper html and styling to create an interactive and human readable version of the JSON.

See the problem here? What gets reported to your upload-complete event listener isn’t the original JSON, but the HTML-wrapped JSON. This can lead to what can only be described as multiple hours of FAIL in which you try and figure out why your JSON response can’t be parsed and used in your javascript.