webpage refresh after function end, And XMLHttpRequest function not work
unless delay added
My webpage restarts/refresh after the function finish running, and I have
no idea why. This function takes some information from a form and sends it
to server. Also the only way for this function to reach inside
if(xmlhttp.readyState==4 && xmlhttp.status==200){ is to add a "delay"
before the function end. Without the delay it seems that when server
response, since the function already 'ended', the
xmlhttp.onreadystatechange=function() is already out of the function stack
or something? therefore could never reach inside the if statement
here is the function: inside head tag:
function sendLogin(){
var xmlhttp;
var getString;
var url = "server/login.php";
var username=document.getElementById('name').value;
var password=document.getElementById('pw').value;
url= url+ "?username="+username+"&password="+password;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera,
Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("get", url , true);
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
getString = xmlhttp.responseText;
alert(getString);
}
};
xmlhttp.send();
//necessary delay
for(var i =0; i <10; i++){
alert('login5');
}
}
here is the form (inside body tab):
<div class="LogIn">
<form id="logInBoxes">
<input type="text" placeholder="username" id='name' size="15px">
<input type="password" placeholder="password" id='pw'
size="10px">
<input type="submit" value="Log In" onclick='sendLogin()'>
</form>
so the two questions are:
why is my page refreshing every time the function call ends
How to get rid of the delay right before the function end and still be
able for it to function properly, i.e. reach inside
if(xmlhttp.readyState==4 && xmlhttp.status==200) when server responses
No comments:
Post a Comment