I'm currently trying to develop a small website in PHP to test my skills. However I found myself stuck when I decided to implement a live username availability check for the sign up process, as my JavaScript knowledge is somewhat basic.
Right now when I put some name in the username field, I only get the loading image and nothing else. This is what I have done:
My login.php page stored in the /views folder:
<section>
<div>
<form action="?action=login" method="post">
<input type="text" placeholder="username" name="username" id="username" onkeypress ="check()">
<span id="usernameStatus"></span>
</form>
</div>
</section>
My js file stored in /views/js:
function check () {
var status = document.getElementById('usernameStatus');
var u = document.getElementById('username').value;
if(u != ""){
status.innerHTML = '<img src="views/img/wait.gif" alt="" height="20" />';
var hr = new XMLHttpRequest();
hr.open("POST", "../login.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
status.innerHTML = hr.responseText;
}
}
var v = "checkName="+u;
hr.send(v);
}
}
And finally the loginController.php stored in /controllers:
public function run() {
if(!empty($_POST["checkName"])){
$name= htmlentities($_POST["checkName"]);
if(Db::getInstance()->username_ok($name)){
echo ("<strong>" . $name . "</strong> unavailable");
}
else{
echo ("<strong>" . $name . "</strong> available");
}
}
require_once('views/login.php');
}
Could someone explain me what have I done wrong? Thanks!