I'm experiencing a weird behaviour while developing a "simple" javascript application. A function sends to a .php page a request with some parameters, via the classical Ajax/POST method.
function sendRequest(params, doAsync, onSending, onDone)
{
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState < 4) {
if(typeof onSending == "function") onSending();
}
else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(typeof onDone == "function") {
var resultCode = xmlhttp.responseXML.documentElement.getAttribute("result");
var content = xmlhttp.responseXML.documentElement.childNodes;
onDone(resultCode, content);
}
}
}
xmlhttp.open("POST", "mypage.php", doAsync);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
The php page processes it and return a simple result in XML form like this:
<?xml version="1.0" encoding="utf-8"?>
<MYreply result="0"/>
Well... this method works fine under IE and Firefox, but not on Chrome, that says "Cannot read property 'documentElement' of null" (=> responseXML is null).
I read that setRequestHeader
functions are not totally supported by Chrome (see WebKit "Refused to set unsafe header 'content-length'"). In fact, Chrome gives errors when executing, but removing those lines causes the application to fail under IE and Firefox too.
So... what's the cross-compatible way to make an Ajax/POST request and get the relative XML response?
P.S.: I don't want to use jQuery library or other external libs ;)