AJAX availability check with submit button
-
test1.php
<html> <head> <script type="text/javascript" src="js/jquery-1.11.1.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#username').change(function(){ var userName = $('#username').val(); $.post("getUserName.php", {userName: userName}, function(data){ $("#userNameCheck").html(data); }); }); $('#submit').click(function(){ //CODE HERE }); }); </script> </head> <body> <form action="" method="post" id="addform"> Username: <input type="text" name="username" id="username" size="24" class="required" maxlength="22" /> <div id="userNameCheck"></div> <input type="submit" id="submit" name="submit" value="ADD user" /> </form> </body> </html>
-
getUserName.php
<?php include("db.php"); $userName = $_POST['userName']; $q = "select user_name from user where user_name = '".$userName."'"; $r = mysqli_query($dbc, $q); $num = mysqli_num_rows($r); if($num) { echo '<div style="color:red">Username taken. Please type another new one. </div>'; } else { echo '<div style="color:green">You can use it.</div>'; } ?>
-
database (user table)
user_id user_name
1 ali
2 abu -
From the above:
=> enter " ali " in the textbox → show the "You can use it" messsage in green.
=> enter ahmad in the textbox → show the message "Username ..." in red. -
My requirement: if the message is "You can use it" go to test2.php; if the message is "Username taken ...", no form claim.
-
My question is, how can I manage the "You can use it" or "Username" message when I click the "Submit" button?
+3
source to share
1 answer
Instead of using a click handler for the button, use the form submit event.
$(document).ready(function () {
$('#username').change(function () {
var userName = $('#username').val();
$.post("getUserName.php", {
userName: userName
}, function (data) {
$("#userNameCheck").html(data);
});
});
$('#addform').submit(function () {
//if the text is `You can use it` allow the form submit else block it
return $("#userNameCheck").html().trim() == 'You can use it';
});
});
Also make sure you are doing the same validation in test2.php
, because client side validation can be done on the side.
+2
source to share