jQuery和PHP验证问题? [英] JQuery and PHP validation problem?
问题描述
我想在PHP端进行验证,然后在单击提交"按钮时让我的JQuery代码显示为your changes have been saved
,但是JQuery代码指出即使验证失败也保存了更改.
I want to do the validation on my PHP side and then have my JQuery code display your changes have been saved
when the submit button is clicked but the JQuery code states that the changes have been saved even when the validation fails.
我该如何解决这个问题,以便PHP可以进行验证,然后在PHP完成验证后JQuery可以执行其工作?
How can i fix this so that PHP can do the validation and then JQuery can do its thing when PHP has finished its validation?
这是我的Jquery代码.
Here is my Jquery code.
$(function() {
$('#changes-saved').hide();
$('.save-button').click(function() {
$.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(html) {
$('div.contact-info-form').html(html);
$('#changes-saved').hide();
$('#changes-saved').html('Your changes have been saved!').fadeIn(4000).show();
});
$('a').click(function () {
$('#changes-saved').empty();
$('#changes-saved').hide();
});
return false; // prevent normal submit
});
});
这是我的PHP代码的一部分.
Here is part of my PHP code.
// Check for an email address:
if (preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $_POST['email'])) {
$email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email']));
} else {
echo '<p class="error">Please enter a valid email address!</p>';
}
推荐答案
,您可以在jquery中添加if语句,以检查php验证是否通过, 在php中,您需要返回一个值,例如1 \ 0或true \ false.
in the jquery you can add a if statment that check if the php validation pass, in the php you need to return a value like 1\0 or true \ false.
并在jquery中检查此参数
and check this parameter in jquery
我使用json添加示例,但这是同样的问题
i add example its using json but is the same issue
jquery:
$.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(data_pack){
if(data_pack.msg ==1){
# success do something ....
.........
}
alert(data_pack.html);
}, 'json');
类似于的php代码:
if($validation_ok){
$arr = array('msg'=>1,'html'=>$html);
}
else {
$arr = array('msg'=>0,'html'=>$error_msg);
}
echo json_encode($arr);
exit;
这篇关于jQuery和PHP验证问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!