added error handling that copes with AJAX