- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 html 表单用作订阅表单。表单通过 POST 方法发送到 PHP 文件进行处理和数据库输入。表单验证是通过 JavaScript 完成的。
我不想重定向到 PHP 文件,我想保留我的表单样式。也就是说,当用户单击“提交”按钮时,表单会动画化并在页面上显示成功消息,而无需重新加载或发送到 php 文件。
我单独测试了 PHP 文件,它工作正常,在 mySQL 数据库表中按预期写入。JavaScript 验证文件本身也能很好地工作。问题是,当单击“提交”按钮时,在所有必填字段均有效后,表单会显示动画,就好像数据已成功发送一样,但没有数据写入我的数据库。我尝试在 JavaScript 代码的不同位置插入不同格式的 AJAX,但没有任何效果。
JS 验证文件链接到 HTML 文件中的 via。并且通过 Form Action=""属性链接到 PHP 文件。
当我在指向 form.js 的链接旁边的 HTML 中使用以下脚本时:
<script type="text/javascript">
$("#submitBtn").click(function() {
var dataString = $('#register').serialize();
$.ajax({
type: "POST",
url: "contact/validate.php",
data: dataString
});
});
</script>
它确实有效 - 表单按预期进行动画处理,没有重定向到 PHP 文件并且表单数据被写入数据库,但这会产生重复条目并且还允许将无效条目写入数据库,尽管输入字段上由 JavaScript 启动的错误消息。
这是我的 HTML 表单:
<div id="contactForm" class="contactForm">
<div id="formHeader" class="formHeader">
<h2 id="message">Форма за регистрация</h2>
</div>
<div id="formBody" class="formBody">
<form action="contact/validate.php" method="POST" name="contactForm" id="register">
<div class="row">
<div class="inputContainer hlf">
<input name="fullname" id="fullname" type="text" placeholder="Вашето име" minlength="2" maxlength="40" required tabindex="1">
</div>
<div class="inputContainer hlf">
<input name="location" id="location" type="text" placeholder="Населено място" minlength="5" maxlength="40" required tabindex="2">
</div>
</div>
<div class="row">
<div class="inputContainer hlf">
<input name="email" id="email" type="email" placeholder="Ваш имейл за контакт" maxlength="75" required tabindex="3">
</div>
<div class="inputContainer hlf">
<input name="phone" id="phone" type="tel" placeholder="Телефон" pattern="[0-9 ]" maxlength="15" tabindex="4">
</div>
</div>
<div class="row">
<div class="inputContainer">
<textarea name="comment" id="comment" rows="4" placeholder="Допълнителен коментар" minlength="5" maxlength="250" tabindex="5"></textarea>
</div></div>
<input id="submitBtn" class="submitBtn" type="submit" value="Изпрати">
</form>
</div>
这是我的 PHP 文件:
<?php
//Clean form data from backslashes and evil tags
//define variables and set to empty values
$fullname = $location = $email = $phone = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fullname = test_input($_POST["fullname"]);
$location = test_input($_POST["location"]);
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$comment = test_input($_POST["comment"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//All input is tested and validated, now connect to DB and send data to the mySQL database table:
$servername = "localhost";
$username = "usename";
$password = "password";
$dbname = "database name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO subscribed (fullname, location, email, phone, comment)
VALUES ('$fullname', '$location', '$email', '$phone', '$comment')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
最后,这是我的 JavaScript 验证文件:
$(function() {
"use strict";
var //GLOBAL VARIABLES
input,
container,
//CSS CLASSES
classSuccess = "success",
classError = "error",
//FORM VALIDATOR
formValidator = {
init: function() {
this.cacheDom();
this.bindEvents();
},
cacheDom: function() {
//MAIN PARENT ELEMENT
this.contactForm = document.getElementById("contactForm");
//MAIN FORM ELEMENTS
this.formHeader = document.querySelector("#formHeader h2");
this.formBody = document.getElementById("formBody");
this.inputContainer = document.getElementsByClassName("inputContainer");
//USER INPUT ELEMENTS
//INPUT FIELDS
this.fields = {
fullname: document.getElementById("fullname"),
location: document.getElementById("location"),
email: document.getElementById("email")
};
this.submitBtn = document.getElementById("submitBtn");
},
bindEvents: function() {
var i;
//RUN RULES ON SUBMIT BUTTON CLICK
this.submitBtn.onclick = this.runRules.bind(this);
//BIND EVENTS TO EACH INPUT FIELD
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
//VARIABLES
input = this.fields[i];
container = input.parentElement;
//RUN RULES WHEN INPUT HAS FOCUS
input.onfocus = this.runRules.bind(this);
//RESET ERRORS WHEN CONTAINER IS CLICKED
container.onclick = this.resetErrors.bind(this, input);
}
}
},
runRules: function(evnt) {
var target = evnt.target,
type = evnt.type;
//IF EVENT ON SUBMIT BUTTON
if (target === this.submitBtn) {
//PREVENT FORM SUBMITTION
this.preventDefault(evnt);
//IF INPUT HAS FOCUS
} else if (type === "focus") {
//RESET CLASSLIST
this.resetClassList(target.parentElement);
//RESET ERRORS
this.resetErrors(target);
return false;
}
//RESET CLASSLIST
this.resetClassList();
//CHECK FIELDS
this.checkFields();
},
preventDefault: function(evnt) {
//PREVENT DEFUALT
evnt.preventDefault();
},
checkFields: function() {
var i,
validCount = 0,
//EMAIL FILTER
filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//CYLCE THROUGH INPUTS
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
input = this.fields[i];
//CHECK IF FIELD IS EMPTY
if (input.value === "") {
//ADD ERROR CLASS
this.addClass(input, classError);
//CHECK IF EMAIL IS VALID
} else if (i === "email" && !filter.test(input.value)) {
//ADD ERROR CLASS
this.addClass(input, classError);
} else {
//FIELD IS VALID
this.addClass(input, classSuccess);
validCount += 1;
}
}
}
//IF ALL FIELDS ARE VALID
if (validCount === 3) {
//SUBMIT FORM
this.submitForm();
}
},
addClass: function(input, clss) {
container = input.parentElement;
//IF INPUT HAS ERROR
if (clss === classError) {
//SHOW ERROR MESSAGE
this.errorMessage(input);
}
//ADD CLASS
input.parentElement.classList.add(clss);
},
errorMessage: function(input) {
var message;
//IF NAME HAS ERROR
if (input === this.fields.fullname) {
message = "Моля, въведете пълно име";
//ELSE IF LOCATION HAS ERROR
} else if (input === this.fields.location) {
message = "Моля, въведете град/село";
//ELSE IF USEREMAIL HAS ERROR
} else if (input === this.fields.email) {
message = "Има грешка в имейла";
}
this.renderError(input, message);
},
renderError: function(input, message) {
var html;
//GET INPUT CONTAINER
container = input.parentElement;
//RENDER HTML
html = document.createElement("div");
html.setAttribute("class", "message");
html.innerHTML = message;
//IF MESSAGE ELEMENT DOESN'T EXIST
if (!container.getElementsByClassName("message")[0]) {
//INSERT MESSAGE TO INPUT CONTAINER
container.insertBefore(html, container.firstElementChild);
}
},
resetClassList: function(input) {
var i;
//IF TARGETING SPECIFIC INPUT
if (input) {
//GET INPUT CONTAINER
container = input.parentElement;
//REMOVE CLASSES
container.classList.remove(classError, classSuccess);
//FOCUS ON INPUT FIELD
input.focus();
} else {
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
//REMOVE CLASSES FROM ALL FIELDS
this.fields[i].parentElement.classList.remove(classError, classSuccess);
}
}
}
},
resetErrors: function(input) {
//GET INPUT CONTAINER
container = input.parentElement;
//IF CONTAINER CONTAINS ERROR
if (container.classList.contains(classError)) {
//RESET CLASSES
this.resetClassList(input);
}
},
submitForm: function() {
var waitForAnimation;
//ADD SUCCESS CLASS
this.contactForm.classList.add(classSuccess);
//WAIT FOR ANIMATION TO FINISH
this.changeHeader("Регистрацията е успешна!");
//WAIT FOR ANIMATION TO FINISH
setTimeout(this.changeHeader.bind(this, "ДОБРЕ ДОШЛИ!"), 1800);
},
changeHeader: function(text) {
//CHANGE HEADER TEXT
this.formHeader.innerHTML = text;
}
};
//INITIATE FORM VALIDATOR
formValidator.init();
}());
最佳答案
<!DOCTYPE html>
<html>
<head>
<title>Task 1</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function()
{
$("#submit").click(function()
{
if($("#fname").val()=="")
{
alert("First name missing");
return false;
}
if($("#lname").val()=="")
{
alert("Last name missing");
return false;
}
var x= jQuery("input[name=gender]:checked").val();
if(!x)
{
alert("Gender missing");
return false;
}
var x= jQuery("input[type=checkbox]:checked").val();
if (!x)
{
alert("Hobbies not selected");
return false;
}
if($("#education").val()=="")
{
alert("Select Education");
return false;
}
else
{
return true;
}
});
});
</script>
</head>
<body>
<form action="insert.php" method="POST" name="myform">
<table border="2" cellspacing="5" cellpadding="5" align="center">
<tr>
<td>
Enter first name:
</td>
<td>
<input type="text" name="fname" id="fname">
</td>
</tr>
<tr>
<td>
Enter last name:
</td>
<td>
<input type="text" name="lname" id="lname">
</td>
</tr>
<tr>
<td>
Select gender:
</td>
<td>
<input type="radio" name="gender" value="male" id="gender">Male
<input type="radio" name="gender" value="female">Female
</td>
</tr>
<tr>
<td>
Select hobbies:
</td>
<td>
<input type="checkbox" name="hobbies[]" value="cricket" id="hobby">Cricket
<input type="checkbox" name="hobbies[]" value="hockey">Hockey
<input type="checkbox" name="hobbies[]" value="swimming">Swimming
</td>
</tr>
<tr>
<td>
Select education:
</td>
<td>
<select name="education" id="education">
<option value="">Select...</option>
<option value="MCA">MCA</option>
<option value="BCA">BCA</option>
<option value="BE">BE</option>
</select>
</td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" name="submit" value="Submit" id="submit">
</td>
</tr>
</table>
</form>
</body>
</html>
关于javascript - 通过 PHP 在 JavaScript 验证后将表单数据发送到 mySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39817439/
在 JSF2 应用程序中遇到验证属性的问题时,有两种主要方法。 使用 Annotation 在 ManagedBean 上定义验证 @ManagedBean public class MyBean {
我想实现一个不常见的功能,我认为 jquery 验证插件将是最好的方法(如果您在没有插件的情况下建议和回答,我们也会欢迎)。我想在用户在输入字段中输入正确的单词后立即隐藏表单。我试过这个: $("
我有几个下拉菜单(类名为month_dropdown),并且下拉菜单的数量不是恒定的。我怎样才能为它们实现 NotEqual 验证。我正在使用 jQuery 验证插件。 这就是我写的 - jQuery
我设法制作了这个网址验证代码并且它起作用了。但我面临着一个问题。我认为 stackoverflow 是获得解决方案的最佳场所。 function url_followers(){ var url=do
我目前正在使用后端服务,该服务允许用户在客户端应用程序上使用 Google Games 库登录。 用户可以通过他们的 gplay ID 向我们发送信息,以便登录或恢复旧帐户。用户向我们发送以下内容,包
我正在尝试验证输入以查看它是否是有效的 IP 地址(可能是部分地址)。 可接受的输入:172、172.112、172.112.113、172.112.113.114 Not Acceptable 输入
我从 Mongoose 验证中得到这条消息: 'Validator failed for path phone with value ``' 这不应该发生,因为不需要电话。 这是我的模型架构: var
我一直在尝试使用Python-LDAP (版本 2.4.19)在 MacOS X 10.9.5 和 Python 2.7.9 下 我想在调用 .start_tls_s() 后验证与给定 LDAP 服务
我正在处理一个仅与 IE6 兼容的旧 javascript 项目(抱歉...),我想仅在 VS 2017 中禁用此项目的 ESLint/CSLint/Javascript 验证/CSS 验证。 我知道
我正在寻找一种方法来验证 Spring 命令 bean 中的 java.lang.Double 字段的最大值和最小值(一个值必须位于给定的值范围之间),例如, public final class W
我正在尝试在 springfuse(JavaEE 6 + Spring Framework (针对 Jetty、Tomcat、JBoss 等)) 和 maven 的帮助下构建我的 webapps 工作
我试图在我们的项目中使用 scalaz 验证,但遇到了以下情况: def rate(username: String, params: Map[String, String]): Validation
我有一个像这样的 Yaml 文件 name: hhh_aaa_bbb arguments: - !argument name: inputsss des
我有一个表单,人们可以单击并向表单添加字段,并且我需要让它在单击时验证这些字段中的值。 假设我单击它两次并获取 2 个独立的字段集,我需要旋转 % 以确保它在保存时等于 100。 我已放入此函数以使其
在我的页面中有一个选项可以创建新的日期字段输入框。用户可以根据需要创建尽可能多的“截止日期”和“起始日期”框。就像, 日期_to1 || date_from1 日期到2 ||日期_from2 date
我有一个像这样的 Yaml 文件 name: hhh_aaa_bbb arguments: - !argument name: inputsss des
有没有办法在动态字段上使用 jquery 验证表单。 我想将其设置为必填字段 我正在使用 Jsp 动态创建表单字段。 喜欢 等等...... 我想使用必需的表单字段验证此表单字段。 最佳答
嗨,任何人都可以通过提供 JavaScript 代码来帮助我验证用户名文本框不应包含数字,它只能包含一个字符。 最佳答案 使用正则表达式: (\d)+ 如果找到匹配项,则字符串中就有一个数字。 关于J
我有两个输入字段holidayDate和Description(id=tags) $(document).ready(function() {
我遇到了这个问题,这些验证从电子邮件验证部分开始就停止工作。 我只是不明白为什么即使经过几天的观察,只是想知道是否有人可以在这里指出我的错误? Javascript部分: function valid
我是一名优秀的程序员,十分优秀!