Refactored the javascript and added a proper response to error responses