Refactored code, handling ajax queries