Make server errors return JSON if requested via AJAX

Our default error handler is popping up rendered HTML error pages because our error handlers are returning HTML. It would be much saner to return JSON when requested via AJAX, even on errors. This pull request makes that happen.