PHP/MySQL.
I have created a simple form containing a username textfield and a button. Page name is checkusername.php. I wrote an AJAX function also. Then I have another page usercheckpage.php to where value from checkusername.php is passed via the AJAX function getResult()
.
In usercheckpage.php, username is checked in the database table, if it is already present, then 'username not available'
is shown and if available 'username available'
is shown.
BUT THE PROBLEM IS, even if the alert message 'username not available'
is displayed, if I click the submit button, the value is passed into my next page insertusername.php. I don't want the form to get submitted if username is not avaiable. I tried html5 validation. But it didn't quite work well.
Here is my code:
checkusername.php
<form id="form1" name="form1" method="post" action="../controller/insertusername.php">
label for="txtuname"></label>
<input type="text" name="txtuname" id="txtuname" required onblur="getResult(this.value);" />
<span id="showusername"></span>
<input type="submit" name="submit" id="submit" value="SUBMIT" />
</form>
AjAX FUnction
function getResult(uname)
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()//callback fn
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('showusername').innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET","checkusername.php?variable="+uname,true);
xmlhttp.send();
}
checkusername.php
<?php
include '../model/Query.php';
$un=$_GET["variable"];
$name="select username from login where username='".$un."'";
$res=getData($name);
while($row=mysqli_fetch_array($res))
{
$name1=$row["username"];
}
if($un==$name1)
{
echo "name already exist";
}
else
{
echo "ok";
}
?>