我有这个小代码(我的注册码的一部分):
<?php
if (@$_POST['Submit'] == 'Register'){
if (strcmp(md5($_POST['user_code']),$_SESSION['ckey']))
{
die("Invalid code entered. Please enter the correct code as shown in the Image");
}
}
?>
<form name="form1" id="signupForm" method="post" action="register.php" style="padding:5px;">
<div class="reg_left">Security code:</div>
<div class="reg_right"><input name="user_code" type="text" size="10"> <img src="pngimg.php" align="middle" width="100" height="40"></div>
<div><input type="submit" name="Submit" class="submit" value="<?php echo $gomb_reg;?>"></div>
</form>
不幸的是,在发布表单数据后检查代码是否有效。我想在发布之前检查一下。
所以我认为我必须使用jQuery验证插件(顺便说一句,我使用jQuery来验证其他字段,如电子邮件,用户,密码)。但由于我不是jQuery的专家,我需要帮助在jQuery中编写上面的php代码。
谢谢。
答案 0 :(得分:1)
我相信基本的主旨是:
(注意:由于jQuery AJAX函数不停止执行脚本,您必须停止提交表单,然后提交表单AJAX回调。)
答案 1 :(得分:1)
您可以保留大部分PHP代码,但是您需要检查请求标头类型。
我很确定jQuery发送X-Requested-With:XMLHttpRequest但是我并不完全确定它已经晚了,所以要稍微修改你的php脚本它会看起来像这样
if (@$_POST['submit'] == 'Register') {
if (strcmp(md5($_POST['user_code']),$_SESSION['ckey']))
{
// check if the request was from an ajax call
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
//if it is an ajax request we need to send back a json encoded array
$response = array('success' => 'true', 'message' => 'Invalid code';
// now we encode the array and echo it back
echo json_encode($response);
// exit the script for safety
exit();
} else {
// if the request wasn't ajax the respond business as usual
die("Invalid code entered. Please enter the correct code as shown in the Image");
}
}
}
至于jQuery代码,它可能看起来像这样:
$(document).ready(function(){
// this creates an event handler on the form submit
$('#signUpForm').submit(function(){
// you'll need to give your user_code input an id of user_code
var user_code = $('#user_code').val();
// I like to use the jQuery $.ajax method since it gives you more controll
$.ajax({
// send a post request
type : 'POST',
// the url you'll be sending the request too
url: 'register.php',
// the type of data you're expecting back
// i prefer json since its easier to work with for me
dataType : 'json',
// the data you want to send which would be your user_code data
// send this in a name/value pair
data : 'user_code=' + user_code + '&submit=Register',
// the success function is called when the ajax call has been
// completed, not whether the user_code matches the $_SESSION['ckey']
// the data variable will contain your json data
success : function(data, textStatus){
// since we json encoded the php array it will
// look something like this
//{ success : 'true', message : 'incorrect code'}
if(data.success == 'true'){
// what you plan on doing if the code is correct
alert(data.message);
} else {
// what you do if the code is incorrect
alert(data.message);
}
}
});
// stop the form from submitting
return false;
});
});
我认为应该这样做。 $ .ajax方法还有一些其他回调函数,例如onError,完整和类似的消息,值得研究here。 $ .ajax方法起初有点令人生畏,但在使用它几次之后,我现在比它们拥有的其他ajax方法($.load,$.get,$.getJSON更喜欢它,或$.post)