Refactored code to return either HTML or JSON for Ajax calls.