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??
First,
is executed whenever the state changes and it the statusses aren't
4
and200
. It does not necessarily meanNot connected
. You could just remove that part. You are currently seeing it three times as the status changes from0
to1
to2
to3
(and4
but that doesn't go to theelse
).Secondly, you are using
.equals
but this function is not natively available and you also don't have it defined. Are you looking for:==
is the equality operator. And,it is not a function so you should not append
()
.