Response text comparision

340 views Asked by At

i am practicing AJAX, in that i written a code to get the text from a file in server and if it is "0" print"zero" or print "one" if error print "not connected". but something went wrong dont know what only getting not connected even if it is connected..

here is the code:

<html>
<head>
<title>LogIN</title>
<script>
function verify()
            {           
            var xml;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xml=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xml=new ActiveXObject("Microsoft.XMLHTTP");
  }
   xml.onreadystatechange=function()
       {
       if (xml.readyState==4 && xml.status==200)
        {
            var res=xml.responseText();
            if(res.equals("0"))
            {
                document.write("zero");
            }
            else
            {
            document.write("one");
            }
        }
        else
            document.write("Not connected");
        }
  xml.open("GET", "log_verify.txt", true);
  xml.send();
}
function login()
{
//action to login
}
</script>
</head>
<body>
<form>
User name : <input type="text" name="uname" onblur="verify()">
<br>
Pwd    : <input type="password" name="passwd" >
<br>
<input type="button" name="Login" value="Login" onclick="login()">
</form>
</body>
</html>

Getting the output as

Not connectedNot connectedNot connected

but when i just display the response text it gets printed correctly as per the code below

<html>
<head>
<title>LogIN</title>
<script>
function verify()
            {           
            var xml;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xml=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xml=new ActiveXObject("Microsoft.XMLHTTP");
  }
   xml.onreadystatechange=function()
  {
  if (xml.readyState==4 && xml.status==200)
    {
       document.getElementById("myDiv").innerHTML+=xml.responseText;
    }
  } 
  xml.open("GET", "log_verify.txt", true);
  xml.send();
}
function login()
{
//action to login
}
</script>
</head>
<body>
<form>
User name : <input type="text" name="uname" onblur="verify()">
<br>
Pwd    : <input type="password" name="passwd" >
<br>
<input type="button" name="Login" value="Login" onclick="login()">
</form>
<div id="myDiv"><h2>Response text:</h2></div>
</body>
</html>

Getting the output as

Response text:

0

is the problem in javascript coding or somewhere in server response??

2

There are 2 answers

4
pimvdb On BEST ANSWER

First,

    else
        document.write("Not connected");

is executed whenever the state changes and it the statusses aren't 4 and 200. It does not necessarily mean Not connected. You could just remove that part. You are currently seeing it three times as the status changes from 0 to 1 to 2 to 3 (and 4 but that doesn't go to the else).

Secondly, you are using .equals but this function is not natively available and you also don't have it defined. Are you looking for:

 if(res == "0")

== is the equality operator. And,

res = xml.responseText;

it is not a function so you should not append ().

4
Lightness Races in Orbit On

Problem #1

In the first snippet you wrote xml.responseText(), which causes the script to terminate.

In the second snippet you got it right, and wrote xml.responseText. It's a text property, not a function.


Problem #2

Regarding the "Not Connected" messages, there is no problem.

You have assumed that, when onreadystatechange is fired, (xml.readyState==4 && xml.status==200) if connected and the opposite if not connected.

But this is not true.

During an XMLHttpRequest's lifetime, if a connection succeeds, onreadystatechange fires multiple times, tracking the various states of the object as the request proceeds.

These states (which lend their values to .readyState) are listed under section 3.5 of the relevant W3C spec:

  • UNSENT (numeric value 0)

    The object has been constructed.

  • OPENED (numeric value 1)

    The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

  • HEADERS_RECEIVED (numeric value 2)

    All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

  • LOADING (numeric value 3)

    The response entity body is being received.

  • DONE (numeric value 4)

    The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

You use the conditional to perform your code only when the object enters the DONE state, not because any other state indicates failure.

The DONE state has an associated error flag that indicates some type of network error or abortion. It can be either true or false and has an initial value of false.

If you want to look for this failure, check the .state property, which has the following possible values:

  • If the state is UNSENT or OPENED return 0 and terminate these steps.
  • If the error flag is true return 0 and terminate these steps.
  • Return the HTTP status code.

So:

xml.onreadystatechange = function() {
   if (xml.readyState != 4) { // handle DONE only
      return;
   }

   if (xml.status == 0) { // error
      document.getElementById("myDiv").innerHTML += "Connection error"
   }
   else if (xml.status == 200) { // HTTP 200 OK
      document.getElementById("myDiv").innerHTML += xml.responseText;
   }
   else { // some other HTTP code
      document.getElementById("myDiv").innerHTML += "HTTP response code " + xml.status;
   }
}