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

强颜欢笑 提交于 2019-12-11 16:43:22

问题


I have been working on a form that has 2 states: in desktop view, the form slides out from the right side of the screen after 5 seconds upon page load, then the user can click a button to close/open it. In mobile view, the form is triggered by a button and appears as a popup.

While building it, I didn't take into consideration that having the form automatically slide in or pop up on every single page would be an inconvenience. I have used HTML5 session storage to prevent the form from opening automatically on page load if the user has already closed the form.

Now the issue has come up that, if the user actually does fill out the form, the form should never automatically slide out or popup. I'm thinking this will involve somehow setting up a cookie upon the form's submission and maintaining that cookie every time said user visits the site. However, I'm not very familiar with cookies--it's definitely new territory for me as I've never done anything with them before.

As a sidenote, we have SharpSpring integration involved (i.e. the user fills out the form and their data is sent to a SharpSpring account for further marketing use and what not. Not sure if this is useful for my question or not.)

Here is the code for reference:

Bootstrap-style HTML form:

<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>

Here is the jQuery that handles the form animations:

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

The AJAX/jQuery submit code:

;(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));

And lastly, the server side form processing code in 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);
}

回答1:


I found some posts on JavaScript cookie creation and management and decided to go that route. I tested it in four browsers (Chrome, Safari, IE, and FireFox) and it seems to work.

Once the form is successfully submitted, the JS cookie is created:

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

Check if the cookie exists to see if the modal should be automatically opened:

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


来源:https://stackoverflow.com/questions/44805795/silverstripe-php-jquery-once-form-has-been-filled-out-by-user-prevent-it-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!