I am doing a very simple AJAX with javascript demo. My application has an AddCountry page, user selects a country and the states list is dynamically populated via AJAX.
The demo was working nicely until I decided to try something new. Instead of an anonymous callback with the onreadystatechange
event handler, I used a named callback. It gives me this error:
Uncaught InvalidStateError: Failed to read the 'status' property from 'XMLHttpRequest': the object's state must not be OPENED.
Here are two sample codes:
Common part:
<script type="text/javascript">
function createXHR(){
if(window.XMLHttpRequest)
return new XMLHttpRequest();
else
return new ActiveXObject("MSXML2.XMLHTTP");
}
function getStates()
{
alert("inside getStates");
var ajax = createXHR(); // step 1 : create XHR object
alert("XHR:"+ajax);
// step 2: creating the ajax request
var inputVal = document.getElementById("country");
var country = inputVal.value;
alert("Value:"+country);
ajax.open("GET","index.jsp?country="+country, true);
// sending the ajax request
ajax.send(null);
// step 4: monitoring for and updating the response
After that this code is not working:
ajax.onreadystatechange = ajaxCallback();
function ajaxCallback(){
//alert("Response Received:"+ajax.status);
if (ajax.status === 404)
alert("status 404");
if (ajax.readyState === 4 && ajax.status === 404)
{
alert("Response Received; "+ajax.responseText);
document.getElementById("states").innerHTML = ajax.responseText;
}
}
but this works :
ajax.onreadystatechange = function (){
if (ajax.readyState == 4 && ajax.status == 200)
{ document.getElementById("states").innerHTML = ajax.responseText; }
}
Can anybody let me know what is the error here?
Thanks in advance, Navin