我正在尝试制作一个只有输入为email-id的订阅表单。 首先,我使用html和php,它存储了email-id,还检查了所需的参数,如'@'和'。'等
与email-id =“d”一样显示错误
但是一旦我添加了ajax,它就会关注表格中是否存在电子邮件ID,而不是已经订阅的,但有关require参数的功能已停止工作。
与email-id =“d”一样也有效
代码如下:
的index.html
<form class="searchform" method ="post" >
<input id="email" type="email" name="email" required="required" />
<button id="submit" type="submit"> </button>
</form>
Ajax文件: script.js
$(document).ready(function(){
$("#submit").click(function(){
var email = $("#email").val();
var dataString = '&email='+ email ;
if(email=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
Php数据库代码: email.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$username = "myusername";
$password = "mypassword";
$hostname = "localhost";
$dbname= "mydbname";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password,$dbname);
if(! $dbhandle )
{
die('Could not connect: ' . mysql_error());
}
$email=$_POST['email'];
$sql = "INSERT INTO email_table". "(email)". "VALUES ('$email')";
if (mysqli_query($dbhandle, $sql)) {
echo "You have subscribed successfully";
} else {
echo "You have already been subscribed";
}
?>
答案 0 :(得分:0)
您的required="required"
代码中不需要required
,只需<input>
。
答案 1 :(得分:0)
jQuery / JS对HTML表单验证一无所知。因此,您需要使用jQuery / JS进行验证,如:
$('#submit').click(function(){
if($("form")[0].checkValidity()) {
//your form execution code
}else console.log("invalid form");
});
HTML5 validation before ajax submit
您还可以使用AJAX处理来自PHP文件的响应,以检查它是否为空。
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$(".class").html(response);
}
});
PHP文件可以是:
if ($_POST['email'] == "") {
echo 'Please enter an email';
}
&#34;请输入电子邮件&#34;将是错误响应,它将被置于具有class =&#39; class&#39;
的任何内容中