Saturday, 14 September 2013

PHP form submission and AJAX validation

PHP form submission and AJAX validation

Below is basic script to check a username availability.
How can I prevent the form from being submitted if a username is already
taken. Ideally i would like to have a JS alert box pop up.
I've tried to add this to the JS but didn't work:
document.getElementById('submit').disabled
Also I've tried to add onclick="return validate();" to the form itself,
but no luck either: the form still can still get submitted.
<form id="edit" action="edit.php" method="post">
<fieldset>
<label>Username</label> <input type="text" class="input" name="username"
id="username"/><span id="status"></span>
<button type="submit" id="submit" value="add">Save</button>
</fielset>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#username").change(function() {
var username = $("#username").val();
var msgbox = $("#status");
if (username.length >= 4) {
$("#status").html('<img src="images/gif/ajax-loading.gif">');
$.ajax({
type: "POST",
url: "ajax_check.php",
data: "username=" + username,
success: function(msg) {
if (msg == 'OK') {
msgbox.html('<img src="/images/yes.png">');
return true;
} else {
msgbox.html(msg);
return false;
}
}
});
} else {
$("#status").html('<img src="/images/no.png"><font
color="#cc0000">too
long!</font>');
return false;
}
return false;
});
});
edit.php and ajax_check.php only contains some SQL queries.
Also, some users have JavaScript disabled on their browser, how could I
get around this?

No comments:

Post a Comment