Fix duplicate code and fix XSS bug