I just cant figure out what is wrong with this code.
I am just sending a username and password to the server, then server sending back a response. Server write to database with no problem, but in the client side sometimes it doesn't reach inside the if(xmlhttp.readyState==4 && xmlhttp.status==200)
. And after it execute the line alert('login5')
, the jquery animation reset. I know it is the php problem, but I have no idea why it sometimes works but sometimes doesnt, any help is appreciated.
<script type = "text/javascript">
function sendLogin(){
var xmlhttp;
var getString;
var url = "login.php";
var username=document.getElementById('name').value;
var password=document.getElementById('pw').value;
var 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){
alert("reached inside");
getString = xmlhttp.responseText;
alert(getString);
}
}
xmlhttp.send();
alert('login5');
//problem here, have to wait a while
}
</script>
html code:
<form id="logInBoxes">
<input type="text" placeholder="username" id='name' size="15px">
<input type="password" placeholder="pw" id='pw' size="10px">
<input type="submit" value="Log In" onclick='sendLogin()'>
</form>
php code:
<?php
$username= $_GET['username'];
$password= $_GET['password'];
$salt = mcrypt_create_iv(32, MCRYPT_RAND);
$password = crypt($password, $salt);
$salt = mysql_real_escape_string($salt);
$password = mysql_real_escape_string($password);
$sql = mysqli_connect('localhost','root','','housescale');
// Check connection
if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($sql, "INSERT INTO user (username, password, salt)
VALUE
('$username', '$password','$salt')") or trigger_error(mysql_error());
mysqli_close($sql);
echo $username;
?>
edit: it works if I do alert('login5')
9 more times in a loop. What exactly does this delay fix imply?