在表单上显示表单验证

时间:2015-10-26 22:24:19

标签: javascript php mysql validation

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

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

这是我的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>

&lt;头&gt;,我有

    <!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);
        }

我的Database.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;
    }
}

My 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;
    });
});

我一直在搜索为什么验证消息没有显示在页面本身上。例如,当我使用错误的电子邮件地址提交时,错误消息会显示在新的空白窗口中&#34; {&#34; status&#34;:&#34; error&#34;,&#34; message&# 34;:&#34;电子邮件地址字段不得为空白&#34;}&#34;

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

安娜。

1 个答案:

答案 0 :(得分:0)

首先确保已将Jquery导入到脚本中,并且还要在提交事件中防止提交和刷新页面的表单的默认行为,您可以使用以下命令执行此操作:

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

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