Hi I’m looking to check my database when a user signs up to my website to make sure that the username they chose doesn’t already exist and if it does let them know. My code below isn’t working though the returns in the ajax don’t seem to be returned to my form no matter what i do and the form always submits. Why is this happening? Thank you for any help
HTML
<form name="signup" action="Test1.php" onsubmit="return checkUser();" method="get">
Username: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>
Javascript
<script type="text/javascript" src="jquery-1.7.1.min.js"/></script>
<script type="text/javascript">
function checkUser(){
var userV = document.signup.user.value;
$.ajax({
url: "Test.php",
type: "POST",
data: {user:userV},
success: function (response) {
if(response=="0"){
//Username already exists notify user
return false;
}else{
return true;
}
}
});
}
</script>
Test.php
<?PHP
$user = $_POST['user'];
if($user=="test"){
die("0");
}else{
die("1")
}
?>
Test1.php
<?PHP
echo "Form submitted";
?>
You put the
returnvalue inside thesuccesscallback of your ajax call, whose execution is delayed till server answers.onsubmit="return checkUser();"expects atrueorfalsevalue incheckUser()function:Anyway this is an overall bad approach because it relies on intrusive javascript. A better solution would be moving all client side logic out of markup:
HTML
JS
Where the alerts would be a proper message to the user, or a more sophisticate validation – this is just for example’s sake.