Reputation: 13
I have this code:
function loadRegions()
{
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 && xmlhttp.status==200)
{
alert("Ready:"+xmlhttp.status);
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("region");
alert(x[0]);
alert(x[1]);
}
}
var ctrcode = frm.elements['countrycode'];
xmlhttp.open("GET","http://mydomain.gr/regionslist.php?countrycode="+ctrcode.value,true);
xmlhttp.send();
}
I have a select
item in my HTML and when someone selects an item then this function is called to get the regions of this country. I can see from my console that the request is done, but the response is never gotten. My onreadystatechange
function is never called. When I delete xmlhttp.status==200
then the function is called but the xmlDoc
object is null
and xmlhttp.status==0
. The URL I use works if I call it alone. Why does my onreadystatechange
function not work and why does it not return status 200?
Upvotes: 1
Views: 4443
Reputation: 6662
add this line before calling send() function:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
and also set onReadyStateChange function after calling open()
reasons:
1) The responseXML property represents the XML response when the complete HTTP response has been received (when readyState is 4), when the Content-Type header specifies the MIME (media) type as text/xml, application/xml, or ends in +xml. If the Content-Type header does not contain one of these media types, the responseXML value is null.
2) After the initial response, all event listeners will be cleared. Call open() before setting an onreadystatechange listener.
here is references of the first and the second reason
Upvotes: 1