gpt4 book ai didi

javascript - 在表单上显示表单验证

转载 作者:行者123 更新时间:2023-11-29 21:54:01 26 4
gpt4 key购买 nike

我正在尝试实现一个简单的新闻通讯注册表单,用户在其中输入他的电子邮件,然后按“提交”。该电子邮件存储在 MySQL 数据库中,我想向订阅者发送一封确认电子邮件。

我从 https://github.com/pinceladasdaweb/Ajax-PHP-MySQL-Newsletter 上的代码开始。由于某些原因,提交时,验证结果显示在新的空 html 页面上,而我想在初始页面本身上显示确认/验证(在表单上,​​如演示中所示: http://www.pinceladasdaweb.com.br/blog/uploads/ajax-newsletter/

这是我的 HTML 代码:

    <div id="newsletterform">
<div class="wrap">
<h3>Get Email Update</h3>
<p>Lorem ipsum dolor sit amet..</p>
<form action="php/send.php" method="post" id="newsletter" name="newsletter">
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
<input type="submit" value="Subscribe" name="signup-button" id="signup-button">
<span class="arrow"></span>
</form>
<div id="response"></div>
</div>
</div>

在中,我有

    <!DOCTYPE HTML>
<html>
<head>
<!-- <meta http-equiv="X-UA-Compatible" content="IE=edge"> -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="favicon.ico">
<title></title>
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="apple-touch-icon" href="images/touch/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="images/touch/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="images/touch/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="144x144" href="images/touch/apple-touch-icon-144x144.png">
<meta property="og:title" content="">
<meta property="og:description" content="">
<meta property="og:url" content="">
<meta property="og:image" content="">
<meta property="og:site_name" content="">
<meta name="format-detection" content="telephone=no">
<meta name="format-detection" content="address=no">
<link rel="stylesheet" href="css/style.css">
<!--[if lt IE 9]>
<script src="js/html5.js"></script>
<script src="js/respond.js"></script>
<![endif]-->

<link rel="stylesheet" href="/path/to/flickity.css" media="screen">



<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/lib.js"></script>
</head>

我的Send.php

   <?php
require 'Database.class.php';
require 'Newsletter.class.php';

if (!empty($_POST)) {
$email = $_POST['signup-email'];

Newsletter::register($email);
}

我的数据库.class.php

        <?php
class Database
{
private static $dbName = '';
private static $dbHost = '';
private static $dbUsername = '';
private static $dbUserPassword = '';

private static $cont = null;

public function __construct() {
die('Init function is not allowed');
}

public static function connect() {
if (null === self::$cont) {
try {
self::$cont = new PDO('mysql:host='.self::$dbHost.'; dbname='.self::$dbName, self::$dbUsername, self::$dbUserPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}

public static function disconnect() {
self::$cont = null;
}
}

我的Newsletter.class.php

<?php
class Newsletter
{
private static $email;
private static $datetime = null;

private static $valid = true;

public function __construct() {
die('Init function is not allowed');
}

public static function register($email) {
if (!empty($_POST)) {
self::$email = $_POST['signup-email'];
self::$datetime = date('Y-m-d H:i:s');

if (empty(self::$email)) {
$status = "error";
$message = "The email address field must not be blank";
self::$valid = false;
} else if (!filter_var(self::$email, FILTER_VALIDATE_EMAIL)) {
$status = "error";
$message = "You must fill the field with a valid email address";
self::$valid = false;
}

if (self::$valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$existingSignup = $pdo->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
$existingSignup->execute();
$data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;

if (!$data_exists) {
$sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
$q = $pdo->prepare($sql);

$q->execute(
array(':email' => self::$email, ':datetime' => self::$datetime));

if ($q) {
$status = "success";
$message = "You have been successfully subscribed";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already subscribed";
}
}

$data = array(
'status' => $status,
'message' => $message
);

echo json_encode($data);

Database::disconnect();
}
}
}

和我的 lib.js

$(document).ready(function () {
$('#newsletter').submit(function () {
var $this = $(this),
$response = $('#response'),
$mail = $('#signup-email'),
testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
hasError = false;

$response.find('p').remove();

if (!testmail.test($mail.val())) {
$response.html('<p class="error">Please enter a valid email</p>');
hasError = true;
}

if (hasError === false) {

$response.find('p').remove();
$response.addClass('loading');

$.ajax({
type: "POST",
dataType: 'json',
cache: false,
url: $this.attr('action'),
data: $this.serialize()
}).done(function (data) {
$response.removeClass('loading');
$response.html('<p>'+data.message+'</p>');
}).fail(function() {
$response.removeClass('loading');
$response.html('<p>An error occurred, please try again</p>');
})
}


return false;
});
});

我已经搜索了几个小时为什么验证消息没有显示在页面本身上。例如,当我提交错误的电子邮件地址时,错误消息会显示在新的空白窗口中 "{"status":"error","message":"电子邮件地址字段不得为空"}"

有人可以帮我吗?我不是一个经验丰富的编码员,所以如果是的话。可以纠正我的代码,我将非常感激。我也不知道如何触发向用户发送电子邮件以确认其注册...:/

安娜。

最佳答案

首先确保您已将 Jquery 导入到脚本中,并且在提交事件中,您必须防止提交和刷新页面的表单的默认行为,您可以通过以下方式执行此操作:

$('#newsletter').submit(function (event) {
event.preventDefault();
//the rest of your code goes here.

抱歉我的英语不好,希望这可以帮助你。

关于javascript - 在表单上显示表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33356694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com