Refactored javascript to keep all ajax logic in one place.