我刚刚插入了一个JQuery username check
,它运行良好,问题是即使我的Mysq Database
上存在用户名,我的表单仍在提交,如果存在,我如何将其配置为拒绝提交给我的server side .php file
?
这是我的Jquery插件javascript代码
$(document).ready(function() {
//the min chars for checkusername
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = '<img src="images/checkusername.gif" /> Checking...';
//when button is clicked
$('#check_checkusername_availability').click(function(){
//run the character number check
if($('#checkusername').val().length < min_chars){
//if it's bellow the minimum show characters_error text
$('#checkusername_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#checkusername_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check checkusername availability
function check_availability(){
//get the checkusername
var checkusername = $('#checkusername').val();
//use ajax to run the check
$.post("frontend/functions/f_checkuser.php", { checkusername: checkusername },
function(result){
//if the result is 1
if(result == 1){
//show that the checkusername is available
$('#checkusername_availability_result').html('<span class="is_available"><b>' +checkusername + '</b> is Available</span>');
}else{
//show that the checkusername is NOT available
$('#checkusername_availability_result').html('<span class="is_not_available"><b>' +checkusername + '</b> is not Available</span>');
}
});
}
这是我的html字段
<table border="0" >
<tr>
<td valign="middle"><input class="input_field_12em required userUserName" name="userUserName" id="checkusername"></td>
<td valign="middle"><input type='button' id='check_checkusername_availability' value='Check Availability'></td>
<td><div id='checkusername_availability_result'></div></td>
</tr>
</table>
您可以等待AJAX请求的回调,然后您可以提交表单也可以不提交:
$(function () {
$('form').on('submit', function (event, extra) {
if (typeof extra == 'undefined') {
extra = false;
}
//if no extra argument is passed via `.trigger()` then don't submit the form
return extra;
});
$('#check_checkusername_availability').on('click', function () {
$.ajax({
url : 'frontend/functions/f_checkuser.php',
type : 'post',
data : { checkusername : $('#checkusername').val() },
success : function (serverResponse) {
//now check the serverResponse variable to see if the name exists, if not then run this code:
$('form').trigger('submit', true);
},
error : function (jqXHR, textStatus, errorThrown) { /*don't forget to handle possible errors*/ }
});
});
});
否则,您可以通过设置async:false
来强制AJAX请求同步,但这将锁定浏览器,直到AJAX请求得到解决,这可能是用户什么都做不了的几秒钟。这会给用户留下脚本已损坏的印象。
您没有发布html,但似乎点击id为check_checkusername_availability
的对象会以某种方式触发表单提交。它是一个提交按钮吗?如果是这种情况,只需将其更改为常规按钮即可。并添加回调来处理响应。