1

Ok...so my code is very simple. The only problem is that the function to be called onreadystatechange is never getting executed. I put in an alert to display the readyState and the status of xmlhttp which displayed it as 1 and 0 respectively. I cannot understand why the state is not changing. Also i do know for sure that everything else works fine. I put in alert boxes to display the username that i'm taking from the form...it displays it properly. Please help me out here....i just cannot figure this out...

function checkAvailability() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp) {
        var regform = document.getElementById("regform");
        var username = regform.username.value;
        xmlhttp.open("POST", "http://localhost:8080/UsernameAvailability", true);
        xmlhttp.onreadystatechange = function() {
            alert(xyz);
        }
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send("username=" + username.value);
    }
}
dfsq
  • 191,768
  • 25
  • 236
  • 258
rashmi1412
  • 47
  • 1
  • 8
  • 1
    Are you intentionally building your own ajax function library? If so, that's cool, but if you just need to get ajax functionality and move on with your work, check out jquery.com. – Jonathan M Mar 23 '13 at 14:36
  • @JonathanM Why would anyone use jquery (and put upon themselves the learning curve of that monster), if all you need is calling basic functions like `new XMLHttpRequest()` etc.? My personal rule for such situations is quite simple: If it takes longer to work through the documentation and whatnot of some library than it takes to write the code yourself, write the code yourself. Alone the cryptic `$` syntax etc. scares me away from jquery, which does not even have a well known scope of what it covers and what not... – BitTickler Feb 20 '23 at 12:56
  • @BitTickler, for doing this type of thing and covering all the bases involved, jQuery simplifies things. It's a well-vetted tool. If you don't want to use it, that's ok, too. – Jonathan M Mar 08 '23 at 22:59

1 Answers1

4

You need switch the calling order of xmlhttp.onreadystatechange and xmlhttp.open to make sure the onreadystatechange callback is registered before opening.

xmlhttp.onreadystatechange = function() {
  alert(xyz);
};
xmlhttp.open("POST", "http://localhost:8080/UsernameAvailability", true);
Shuping
  • 5,388
  • 6
  • 43
  • 66
  • ok...so now i just separated it out and created another function to be called onreadystatechange and surprise surprise!! the alert works. But my job doesnt end there...i need to do some processing when the readyState == 4 and the status ==200 and these conditions arent getting satisfied. The values of readyState and status just remain 1 and 0... – rashmi1412 Mar 23 '13 at 15:04