【发布时间】:2015-11-09 10:06:45
【问题描述】:
好吧,兄弟们,我对有关表单验证的通知的外观有疑问。我将问题与 php 代码上的一些问题联系起来,例如由变量 $errors 和 $data 定义的数组。我真的不明白它们的用途。或者它可能与 jQuery 代码中的某个地方有关。
这些代码基于我在互联网上找到的网站教程。另外,我在 Ajax 和 jQuery 领域没有经验。也许你可以解决这个简单的问题。我什至附加了注册页面的屏幕截图以及处理与数据库的 php 连接的下一页。
This is the sign up page called join_form.php
This is the processing page called register2.php
这是html代码:
<html>
<head>
<title>
This is the form page
</title>
</head>
<body>
<center>
<br>
<br>
<img src="images/quintz.png" width="156" height="44" alt=""/>
<br>
<br>
Register now
<br>
<br>
<div id="bugado">
<form id="ajax_form" method="post" action="register2.php">
<div id="usertype-group" class="form-group">
<label for="usertype">
You're a
</label>
<select name="usertype" class="form-control">
<option value="native speaker">
Native speaker
</option>
<option value="non-native speaker">
Non-native speaker
</option>
</select>
<br>
<!-- errors will go here -->
</div>
<div id="username-group" class="form-group">
<label for="username">
Create username:
</label>
<input name="username" type="text" maxlength="30" class="form-control" placeholder="Username">
<br>
</div>
<div id="email-group" class="form-group">
<label for="email">
Email:
</label>
<input name="email" type="text" maxlength="50" class="form-control" placeholder="Email">
<br>
<!-- errors will go here -->
</div>
<div id="password-group" class="form-group">
<label for="password">
Create password:
</label>
<input type="password" name="password" class="form-control" placeholder="Password">
<br>
</div>
<label>
Confirm password:
</label>
<input type="password" name="confirm_password" class="form-control" placeholder="Password again">
<br>
<button type="submit" name="submit" class="btn btn-success">
Submit
</button>
<span class="fa fa-arrow-right">
</span>
<br>
<input name="reset" type="reset" value="Reset">
</form>
</div>
</center>
</body>
</html>
这是 jQuery 代码:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js"></script>
<script language="javascript">
$(document).ready(function() {
// process the form
$('#ajax_form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'usertype' : $('select[name="usertype"]').val(),
'username' : $('input[name="username"]').val(),
'email' : $('input[name="email"]').val(),
'password' : $('input[name="password"]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : $(form).attr('action'), // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for usertype ---------------
if (data.errors.usertype) {
$('#usertype-group').addClass('has-error'); // add the error class to show red select
$('#usertype-group').append('<div class="help-block">' + data.errors.usertype + '</div>'); // add the actual error message under our select
}
// handle errors for username ---------------
if (data.errors.username) {
$('#username-group').addClass('has-error'); // add the error class to show red input
$('#username-group').append('<div class="help-block">' + data.errors.username + '</div>'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
}
// handle errors for superhero alias ---------------
if (data.errors.password) {
$('#password-group').addClass('has-error'); // add the error class to show red input
$('#password-group').append('<div class="help-block">' + data.errors.password + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('#ajax_form').append('<div class="alert alert-success">' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
alert('success'); // for now we'll just alert the user
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
这是 php 代码:
<?php
include 'db.php';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
//Searching for identical usernames
$search = mysql_query("SELECT * FROM natspeaker WHERE username = '".$_POST['username']."'");
$count = mysql_num_rows($search);
$search2 = mysql_query("SELECT * FROM nonnatspeaker WHERE username = '".$_POST['username']."'");
$count2 = mysql_num_rows($search2);
//Searching for identical emails
$search3 = mysql_query("SELECT * FROM natspeaker WHERE email = '".$_POST['email']."'");
$count3 = mysql_num_rows($search3);
$search4 = mysql_query("SELECT * FROM nonnatspeaker WHERE email = '".$_POST['email']."'");
$count4 = mysql_num_rows($search4);
//if( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST' ) {
if(isset($_POST)){
//USERTYPE
if(empty($_POST['usertype'])) {
$errors['usertype'] = "Please select if you are a native or a non-native speaker.<br>";
}
//USERNAME
if (empty($_POST['username'])) {
$errors['username'] = "Username is missing<br>";
}else{//this "else" can be deleted
/*this can be deleted in case of trouble*/if ( $count == 1 OR $count2 == 1) {
$errors['username'] .= "Username already exists in our database. Choose another one<br>";
}
}//this bracket can be deleted.
//EMAIL
if (empty($_POST['email'])) {
$errors['email'] = "Email is missing<br>";
}else{//this "else" can be deleted
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $_POST['email'])) {
$errors['email'] = "Invalid email<br>";
}
if ( $count3 == 1 OR $count4 == 1) {
$errors['email'] = "Email already exists in our database. It seems you have an account yet.<br>";
}
}//this bracket can be deleted.
//PASSWORD
if (empty($_POST['password'])) {
$errors['password'] = "Password is missing.<br>";
}else{//this "else" can be deleted
if (strlen($_POST['password']) < 6) {
$errors['password'] = "Password too short<br>";
}
}//this bracket can be deleted.
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
//if(count($_SESSION['errors']) > 0){
//This is for ajax requests:
if( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST' ) {
//if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])== 'xmlhttprequest') {//something is wrong with this
header('Content-type: application/json');
echo "Ajax request is working.";
echo json_encode($data);//now this iss working
exit;
}
//This is when Javascript is turned off:
echo "<br><br><br><center><div style=\"font-size:50;\">something is wrong or your Javascript is turned off. Ajax request is not working</div></center><br><br>";//delete
echo $data;//delete
//foreach($_SESSION['errors'] as $key => $value){
//echo "<li>" . $value . "</li>";
//}
//echo "</ul>";exit;
}else{
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
if ( $_POST['usertype'] == "native speaker") {
$register = mysql_query("INSERT INTO natspeaker(username, email, password, time1, usertype)
VALUES ('".$_POST['username']."','".$_POST['email']."', '".$_POST['password']."', now(), '".$_POST['usertype']."')") or die (mysql_error());
}elseif ( $_POST['usertype'] == "non-native speaker"){
$register = mysql_query("INSERT INTO nonnatspeaker(username, email, password, time1, usertype)
VALUES ('".$_POST['username']."', '".$_POST['email']."', '".$_POST['password']."', now(), '".$_POST['usertype']."')") or die (mysql_error());
}
// Let's mail the user!
$subject = "Your Membership at Quintz!";
$message = "Hi, ".$_POST['username'].",
Thank you for registering at our website, http://www.quintz.club!
You have registered as a ".$_POST['usertype'].".
You are two steps away from logging in and accessing our exclusive members area.
To activate your membership, please click here: http://www.quintz.club/activate.php
Once you activate your membership, you will be able to login.
And please do not forget to complete your profile.
Thanks!
The Webmaster
This is an automated response, please do not reply!";
mail($_POST['email'], $subject, $message, "From: Quintz Webmaster<support@quintz.club>\nX-Mailer: PHP/" . phpversion());
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Your account has been created successfully. Go to your email address and activate your account.';
echo "successful register!";//delete
}
}
//}
// return all our data to an AJAX call
//this works
//echo json_encode($data);//delete
?>
总而言之,我只是想阻止用户使用数据库中已经存在的用户名,或者使用无效的电子邮件,甚至缺少信息(空白字段)进行注册,并且只是在同一页面中返回那些红色通知join_form.php。如果所有信息都被批准传递到数据库并最终显示消息“注册成功!”,则用户只能转到 register2.php。在此页面上并向用户发送电子邮件。就是这样!
【问题讨论】:
-
有什么错误吗?在您的页面上还是在您的控制台中?
-
我正在使用 fatcow 服务器。我的页面没有错误,只看图片,完全一样。
-
控制台日志(浏览器的开发者工具)怎么样?
-
好的。链接是什么?
-
查看可能从您的 Ajax 中返回的错误。只需在浏览器上点击
F12。
标签: php jquery html mysql ajax