Could anyone explain me why:
function doAjax() { var xmlHttpReq = false; try { // Firefox, Opera 8.0+ and Safari xmlHttpReq = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttpReq = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { alert('Your browser does not support AJAX. Please use an AJAX compatible browser.'); return false; } } } xmlHttpReq.open('GET', 'handler.php', true); xmlHttpReq.onreadystatechange = function() { if (xmlHttpReq.readyState == 4) { var response = xmlHttpReq.responseText; handleAjaxResponse(response); } }; xmlHttpReq.send(null); return true; }
is causing the following validation errors:
Error: Implied global: ActiveXObject 8, XMLHttpRequest 4, alert 15, handleAjaxResponse 24 Problem at line 10 character 16: 'e' is already defined. catch (e) { Problem at line 14 character 20: 'e' is already defined. catch (e) {
by the JSlint.com javascript validator
It would be more sensible to use framework like jQuery (especially if you seriously want to support older versions of IE (pre v6) ) but I’ll assume there is a reason you’re not doing that.
It would be better if a) you don’t nest try-catches and b) you factored out a set of functions namely one to get an Xhr object, another to use an Xhr object to make a generic ajax request and an outer ‘doAjax’ function that performs the specific ajax call you want to make:-
A futher refinement would be to make the callback accept an XHR object rather than the basic responseText. This would give you more flexibility. If the callback function simply wants the text it can use this function:-