Silverstripe/PHP/jQuery - 用户填写表格后,防止每次访问自动出现

Silverstripe/PHP/jQuery - Once form has been filled out by user, prevent it from automatically appearing for each visit

我一直在开发一个有两种状态的表单:在桌面视图中,表单在页面加载 5 秒后从屏幕右侧滑出,然后用户可以单击一个按钮 close/open 它。在移动视图中,表单由按钮触发并显示为弹出窗口。

在构建它时,我没有考虑到让表单在每个页面上自动滑入或弹出会带来不便。如果用户已经关闭表单,我已经使用 HTML5 会话存储来防止表单在页面加载时自动打开。

现在问题来了,如果用户确实填写了表单,表单永远不会自动滑出或弹出。我认为这将涉及以某种方式在提交表单时设置一个 cookie,并在每次所述用户访问该站点时维护该 cookie。但是,我对 cookie 不是很熟悉——这对我来说绝对是一个新领域,因为我以前从未对它们做过任何事情。

作为旁注,我们涉及 SharpSpring 集成(即用户填写表格并将他们的数据发送到 SharpSpring 帐户以供进一步营销使用等等。不确定这对我的问题是否有用.)

参考代码如下:

Bootstrap-style HTML形式:

<div class="mobile-view" style="right: 51px;">
    <a class="mobile-btn">
        <span class="glyphicon glyphicon-arrow-left icon-arrow-mobile mobile-form-btn"></span>
    </a>
</div>
<div class="slider register-photo">
    <div class="form-inner">
        <div class="form-container">
            <form method="post" enctype="multipart/form-data" id="browserHangForm">
                <a class="sidebar">
                    <span class="glyphicon glyphicon-arrow-left icon-arrow arrow"></span>
                </a>
                <a class="closeBtn">
                    <span class="glyphicon glyphicon-remove"></span>
                </a>

                <h2 class="text-center black">Receive a free copy of so-and-so's book!
                </h2>

                <p class="light">-- Free Download --</p>

                <p class="errors-container light">Please fill in the required fields.</p>

                <div class="success">$SiteConfig.GatewayFormThankYou</div>
                <div class="form-field-content">
                    <div class="form-group">
                        <input class="form-control FirstNameTxt" type="text" name="first_name" placeholder="*First Name"
                               autofocus="">
                    </div>
                    <div class="form-group">
                        <input class="form-control LastNameTxt" type="text" name="last_name" placeholder="*Last Name"
                               autofocus="">
                    </div>
                    <div class="form-group">
                        <input class="form-control EmailTxt" type="email" name="Email" placeholder="*Email"
                               autofocus="">
                    </div>
                    <div class="form-group">
                        <input class="form-control CompanyTxt" type="text" name="Company" placeholder="*Company"
                               autofocus="">
                    </div>
                    <div class="form-group submit-button">
                        <button class="btn btn-primary btn-block button-submit" type="button">Send it to me</button>
                        <img src="/themes/simple/images/ajax-loader.gif" class="progress" alt="Submitting...">
                    </div>
                </div>
                <br/>

                <div class="privacy-link">
                    <a href="privacy-policy" class="already" target="_blank"><span
                            class="glyphicon glyphicon-lock icon-lock"></span>We will never share your information.</a>
                </div>
            </form>
            <% if $SiteConfig.GatewayFormEmbedCodeID %>
                <input type="hidden" id="gatewayEmbedID" value="$SiteConfig.GatewayFormEmbedCodeID" />
                <script type="text/javascript">
                    var __ss_noform = __ss_noform || [];
                    __ss_noform.push(['baseURI', 'https://app-3QNAHNE212.marketingautomation.services/webforms/receivePostback/MzawMDEzMDcwBAA/']);
                    __ss_noform.push(['form', 'browserHangForm', '$SiteConfig.GatewayFormEmbedCodeID']);
                    __ss_noform.push(['submitType', 'manual']);
                </script>
                <script type="text/javascript"
                        src="https://koi-3QNAHNE212.marketingautomation.services/client/noform.js?ver=1.24"></script>
            <% end_if %>
        </div>
    </div>
</div>

这是处理表单动画的jQuery:

jQuery.noConflict();

(function ($) {

    $(document).ready(function () {
//This function checks if we are in mobile view or not to determine the
//UI behavior of the form.

        window.onload = checkWindowSize();

        var arrowicon = $(".arrow");
        var overlay = $("#overlay");
        var slidingDiv = $(".slider");
        var closeBtn = $(".closeBtn");
        var mobileBtn = $(".mobile-btn");

//When the page loads, check the screen size.
//If the screen size is less than 768px, you want to get the function
//that opens the form as a popup in the center of the screen
//Otherwise, you want it to be a slide-out animation from the right side
        function checkWindowSize() {
            if ($(window).width() <= 768) {
                //get function to open form at center of screen
                if(sessionStorage["PopupShown"] != 'yes'){
                    setTimeout(formModal, 5000);
                    function formModal() {
                        slidingDiv.addClass("showForm")
                        overlay.addClass("showOverlay");
                        overlay.removeClass('hideOverlay');
                        mobileBtn.addClass("hideBtn");
                    }
                }
            }
            else {
                //when we aren't in mobile view, let's just have the form slide out from the right
                if(sessionStorage["PopupShown"] != 'yes'){
                    setTimeout(slideOut, 5000);
                    function slideOut() {
                        slidingDiv.animate({'right': '-20px'}).addClass('open');
                        arrowicon.addClass("glyphicon-arrow-right");
                        arrowicon.removeClass("glyphicon-arrow-left");
                        overlay.addClass("showOverlay");
                        overlay.removeClass("hideOverlay");
                    }
                }
            }
        }

        /*
         ------------------------------------------------------------
         Functions to open/close form like a modal in center of screen in mobile view
         ------------------------------------------------------------
         */

        mobileBtn.click(function () {
            slidingDiv.addClass("showForm");
            slidingDiv.removeClass("hideForm");
            overlay.addClass("showOverlay");
            overlay.removeClass('hideOverlay');
            mobileBtn.addClass("hideBtn");
        });
        closeBtn.click(function () {
            slidingDiv.addClass("hideForm");
            slidingDiv.removeClass("showForm");
            overlay.removeClass("showOverlay");
            overlay.addClass("hideOverlay")
            mobileBtn.removeClass("hideBtn");
            sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
        });


        /*
         ------------------------------------------------------------
         Function to slide the sidebar form out/in
         ------------------------------------------------------------
         */
        arrowicon.click(function () {
            if (slidingDiv.hasClass('open')) {
                slidingDiv.animate({'right': '-390px'}).removeClass('open');
                arrowicon.addClass("glyphicon-arrow-left");
                arrowicon.removeClass("glyphicon-arrow-right");
                overlay.removeClass("showOverlay");
                overlay.addClass("hideOverlay");
                sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown

            } else {
                slidingDiv.animate({'right': '-20px'}).addClass('open');
                arrowicon.addClass("glyphicon-arrow-right");
                arrowicon.removeClass("glyphicon-arrow-left");
                overlay.addClass("showOverlay");
                overlay.removeClass("hideOverlay");
            }

        });

    });


}(jQuery));

AJAX/jQuery提交代码:

;(function ($) {
    $(document).ready(function () {
        var FirstName = $('.FirstNameTxt');
        var LastName = $('.LastNameTxt');
        var EmailAddress = $('.EmailTxt');
        var Company = $('.CompanyTxt');
        var successMessage = $('.success');
        var error = $('.errors-container');
        var sharpSpringID = $('#gatewayEmbedID').val();
        var submitbtn = $('.button-submit');
        var SubmitProgress = $('img.progress');


        function validateForm() {
            var required = [FirstName, LastName , EmailAddress, Company];
            var containsErrors = false;

            for (i = 0; i < required.length; i++) {
                var input = required[i];
                if ((input.val() == "")) {
                    containsErrors = true;
                    input.addClass('error-field');
                    error.show();
                } else {
                    input.removeClass('error-field');
                }
            }

            return !containsErrors;
        }
        submitbtn.click(function(e) {
            var isValid = validateForm();
            if (isValid) {
                postForm();
            }
        });

        function postForm() {
            var formData = {
                firstname: FirstName.val(),
                lastname: LastName.val(),
                useremail: EmailAddress.val(),
                company: Company.val()
            };

            submitbtn.hide();
            error.hide();
            SubmitProgress.show();

            $.ajax({
                type: "POST",
                url: "/home/submitGatewayForm",
                data: formData,
                dataType: "json",
            }).done(function (response) {
                submitbtn.show();
                SubmitProgress.hide();
                for (var i = 0; i < response.length; i++) {
                    var status = response[i].status;
                    if (status == "error") {
                       if (response[i].field == "email") {
                            error.show();
                            EmailAddress.addClass("error-field");
                       }
                    }
                    else if (status == "success") {
                        __ss_noform.push(['submit', null, sharpSpringID]);

                        $('#browserHangForm')[0].reset();
                        $('.form-field-content').hide();
                        successMessage.show();
                        $('.button-submit').html("Submitted");
                    }
                }
            });
        }
    });
}(jQuery));

最后,Page.php中的服务器端表单处理代码:

public function submitGatewayForm() {
    $firstname = $this->getRequest()->postVar('firstname');
    $lastname  = $this->getRequest()->postVar('lastname');
    $emailfield     = $this->getRequest()->postVar('useremail');
    $company   = $this->getRequest()->postVar('company');

    $return = [];

    if (!filter_var($emailfield, FILTER_VALIDATE_EMAIL)) {
        $validatonStatus = "error";
        $errorField = "email";
    }

    else {
        $gatewaysubmission = new GatewayFormSubmission();
        $gatewaysubmission->FirstName = $firstname;
        $gatewaysubmission->LastName = $lastname;
        $gatewaysubmission->Email = $emailfield;
        $gatewaysubmission->Company = $company;
        $gatewaysubmission->write();

        $validatonStatus = "success";
        $errorField = "";

        $from = '[email]';
        $to = '[email]';
        $cc = '[email]';
        $subject = 'Gateway Form Submission';

        $body ="Below is the form information submitted by the user:"."<br /><br />";
        $body .= "<strong>First Name:</strong> ".$firstname."<br/>"."<strong>Last Name:</strong> ".$lastname."<br/>"."<strong>Email:</strong> ".$emailfield."<br />"."<strong>Company:</strong> ".$company."<br />";

        $email = new Email($from, $to, $subject, $body);
        $email->setReplyto($emailfield);
        $email->setCc($cc);
        $email->send();

    }
    $return[] = array(
        "status" => $validatonStatus,
        "field" => $errorField,
    );

    return json_encode($return);
}

我发现了一些关于 JavaScript cookie 创建和管理的帖子,并决定走那条路。我在四种浏览器(Chrome、Safari、IE 和 FireFox)中对其进行了测试,它似乎可以正常工作。

成功提交表单后,将创建 JS cookie:

 function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

  $.ajax({
            type: "POST",
            url: "/home/submitGatewayForm",
            data: formData,
            dataType: "json",
        }).done(function (response) {
            submitbtn.show();
            SubmitProgress.hide();
            for (var i = 0; i < response.length; i++) {
                var status = response[i].status;
                if (status == "error") {
                   if (response[i].field == "email") {
                        error.show();
                        EmailAddress.addClass("error-field");
                   }
                }
                else if (status == "success") {
                    __ss_noform.push(['submit', null, sharpSpringID]);
                    //set cookie when the form has been submitted
                    setCookie('ReceivedDownload','PdfSub', 3650);
                    $('#browserHangForm')[0].reset();
                    $('.form-field-content').hide();
                    successMessage.show();
                    $('.button-submit').html("Submitted");
                }
            }
        });

检查 cookie 是否存在以查看模态是否应自动打开:

function checkWindowSize() {
        if ($(window).width() <= 768) {
            //get function to open form at center of screen
            if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
                setTimeout(formModal, 5000);
                function formModal() {
                    slidingDiv.addClass("showForm")
                    overlay.addClass("showOverlay");
                    overlay.removeClass('hideOverlay');
                    mobileBtn.addClass("hideBtn");
                }
            }
        }
        else {
            //when we aren't in mobile view, let's just have the form slide out from the right
            if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
                setTimeout(slideOut, 5000);
                function slideOut() {
                    slidingDiv.animate({'right': '-20px'}).addClass('open');
                    arrowicon.addClass("glyphicon-arrow-right");
                    arrowicon.removeClass("glyphicon-arrow-left");
                    overlay.addClass("showOverlay");
                    overlay.removeClass("hideOverlay");
                }
            }
        }
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    function checkCookie() {
        var user = getCookie("ReceivedDownload");
        if (user != "") {
           return true;
        } else {
            return false;
        }
    }