0

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 ;)

Community
  • 1
  • 1
TheUnexpected
  • 3,077
  • 6
  • 32
  • 62
  • _I don't want to use jQuery library or other external libs_ - why not? This problem is likely solved by any number of cross browser ajax libraries. – jrummell Oct 16 '12 at 18:04
  • I know that it will be very easy if I use jQuery, but for very specific reasons I must not use it ;) – TheUnexpected Oct 16 '12 at 18:58
  • Does your php script output The proper content-type header? I know some browsers may be picky when receiving the wrong content-type header – thaJeztah Jan 27 '13 at 10:54
  • Regarding jQuery; you might *try* if it works with jQuery and then have a look at their source code. A lot of research has gone into jQuery for browser compatibility, so it might be interesting to learn from them :) – thaJeztah Jan 27 '13 at 10:57

1 Answers1

0

use following.

var parent = responseXml.getElementsByTagName("MYreply");
var resultvalue = parent[0].getAttribute('result');
Shmidt
  • 16,436
  • 18
  • 88
  • 136
rahul pasricha
  • 931
  • 1
  • 14
  • 35