I have a problem with an AJAX call that i make to login a user. The code looks like this:
function loginUser()
{
var xmlhttp;
if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//alert(xmlhttp.responseText);
var responseString = xmlhttp.responseText;
if(responseString.indexOf("loginStatus:approved") != -1) {
document.getElementById("logInBar").innerHTML = "Welcome " + getCookie("userLoggedOnfn") + " <a href=\"logoutUser.php\">Logout</a>";
}
}
}
var params = "loginUsername=" + document.getElementById("loginUsername").value +
"&loginPassword=" + document.getElementById("loginPassword").value +
"&d=" + new Date().getTime();
//alert(params);
xmlhttp.open("POST", "loginUser.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
//alert("."); //this alert box is needed to make it work if it's asynchronous
}
The problem is that if i have it like this, it never reaches readyState == 4, or 3 for that matter… it only gets to 2. And if I break the js operations before it reaches readyState == 3 in the debugger in chrome, it gets to readyState == 4. And if I do it synchronous, it works, or if I add the alert box in the end… it’s like it needs to pause before it can reach readyState == 4 or something… So what I’m i doing wrong?
Btw, i need to do this in pure AJAX because it’s a school assignment…
I found the problem! It was in the html code.
I had the login button and text boxes inside a form tag, and chrome automatically refreshed the whole page when i pressed the button inside the form tag. So the AJAX call was messed up because of the reloading of the page.
I just removed the form tags and the problem was solved.