表单中的必填字段不起作用

Required fields in form doesn't work

我正在尝试制作一个仅输入电子邮件 ID 的订阅表单。 首先,我使用 html 和 php 在其中存储了电子邮件 ID,并且还在检查所需的参数,例如 '@' 和 '.'等等

喜欢 email-id ="d" 显示错误

但是一旦我添加了 ajax,它就会关注 table 中是否存在电子邮件 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";
}
?>

您不需要 required="required",只需 required 在您的 <input> 标签内。

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

您还可以处理来自 PHP 文件的响应,使用 AJAX 检查它是否为空。

$.ajax({
        url: url,
        type: type,
        data: data,
        success: function(response) {
            $(".class").html(response);
        }
    });

PHP 文件可以是:

if ($_POST['email'] == "") {
   echo 'Please enter an email';
}

"Please enter an email" 将是错误响应,它将被放置在具有 class='class'

的任何内容中