Learn-to-send-email-via-google-script-html-no-server: Can't get Ajax to show thank you message

Created on 27 Aug 2018  路  5Comments  路  Source: dwyl/learn-to-send-email-via-google-script-html-no-server

I believe I may have the JAVA script in the wrong place, but I'm not sure since I am inexperienced with JAVA or AJAX

Here is a copy of my contact page

<!DOCTYPE html>
<html lang="en">
<head>
<title>Mama Gina's | Contacts</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/reset.css" type="text/css" media="screen">
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen">
<link rel="stylesheet" href="css/layout.css" type="text/css" media="screen">
<link href='http://fonts.googleapis.com/css?family=Adamina' rel='stylesheet' type='text/css'>
<script src="js/jquery-1.6.3.min.js" type="text/javascript"></script>
<script src="js/cufon-yui.js" type="text/javascript"></script>
<script src="js/cufon-replace.js" type="text/javascript"></script>
<script src="js/Lobster_13_400.font.js" type="text/javascript"></script>
<script src="js/NewsGoth_BT_400.font.js" type="text/javascript"></script>
<script src="js/FF-cash.js" type="text/javascript"></script>
<script src="js/easyTooltip.js" type="text/javascript"></script>
<script src="js/script.js" type="text/javascript"></script>
<script src="js/bgSlider.js" type="text/javascript"></script>
<!--[if lt IE 9]>
<script type="text/javascript" src="js/html5.js"></script>
<link rel="stylesheet" href="css/ie.css" type="text/css" media="screen">
<![endif]-->
</head>
<body id="page6">
    <div id="bgSlider"></div>
    <div class="bg_spinner"></div>
    <div class="extra">
        <!--==============================header=================================-->
        <header>
            <div class="top-row">
                <div class="main">
                    <div class="wrapper">
                        <h1><a href="index.html">Mama Gina's</a></h1>
                        <ul class="pagination">
                            <li class="current"><a href="images/bg-img1.jpg">1</a></li>
                            <li><a href="images/bg-img2.jpg">2</a></li>
                            <li><a href="images/bg-img3.jpg">3</a></li>
                        </ul>
                        <strong class="bg-text">Background:</strong>
                    </div>
                </div>
            </div>
            <div class="menu-row">
                <div class="menu-border">
                    <div class="main">
                        <nav>
                            <ul class="menu">
                                <li><a href="index.html">Main</a></li>
                                <li><a href="about.html">About Us</a></li>
                                <li><a href="order.html">Order</a></li>
                                <li><a href="services.html">Services</a></li>
                                <li><a href="blog.html">Blog</a></li>
                                <li class="last"><a class="active" href="contacts.html">Contacts</a></li>
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </header>
        <!--==============================content================================-->
        <div class="inner">
            <div class="main">
                <section id="content">
                    <div class="indent">
                        <div class="wrapper">
                            <article class="col-1">
                                <div class="indent-left">
                                    <h3>Contact Form</h3>
                                    <div class="p3">
                                        <form class="gform" data-email="[email protected]" method="post" enctype="multipart/form-data" action="https://script.google.com/macros/s/AKfycbwA99DAoedqxZzJTOzyS-2-o1EcXVkjy-X0yenXpTNIiJgUBA/exec">
                                            <fieldset>
                                                <label>
                                                    <span class="text-form">Full Name:</span>
                                                    <input name="p1" type="text" /> <br />
                                                </label>

                                                <label>
                                                    <span class="text-form">E-mail:</span>
                                                    <input name="p2" type="text" />
                                                </label>
                                                <div class="wrapper">
                                                    <div class="text-form">Message:</div>
                                                    <div class="extra-wrap">
                                                        <textarea></textarea>
                                                        <div class="clear"></div>
                                                        <div class="buttons">
                                                            <!--<a class="button-2" href="#">Clear</a> <a class="button-2" href="#">Send</a>-->
                                                            <input type="submit" value="Contact Us">
                                                        </div>
                                                    </div>
                                                </div>
                                            </fieldset>
                                        </form>
                                    </div>
                                </div>
                                <div class="bg">
                                    <div class="padding">
                                        <h3>We would love to hear from you</h3>
                                        Mama Gina鈥檚 will respond to your email within 24 hours, if you would like a phone call please include your number and the best time to call.
                                    </div>
                                </div>
                            </article>
                            <article class="col-2">
                                <h3 class="border-bot indent-bot">Our Contacts</h3>
                                <div class="img-indent-bot">
                                    <h6>USA</h6>
                                    <dl>
                                        <dt>PO Box 170862, Arlington, TX 76003</dt>
                                        <dd><span>Telephone:</span> +1 682 360 3755</dd>
                                        <dd><span>E-mail:</span><a href="[email protected]">[email protected]</a></dd>
                                    </dl>
                                </div>
                                <!--<div class="img-indent-bot">
                                  <h6>Hello</h6>
                                  <dl>
                                    <dt></dt>
                                    <dd><span></span></dd>
                                    <dd><span></span> </dd>
                                    <dd><span></span><a href="#"></a></dd>
                                  </dl>
                                </div>
                                <div class="img-indent-bot">
                                  <h6></h6>
                                  <dl>
                                    <dt></dt>
                                    <dd><span></span></dd>
                                    <dd><span></span> </dd>
                                    <dd><span></span><a href="#"></a></dd>
                                  </dl>
                                </div>
                                <h6></h6>
                                <dl>
                                  <dt></dt>
                                  <dd><span></span></dd>
                                  <dd><span></span></dd>
                                  <dd><span></span><a href="#"></a></dd>
                                </dl>-->
                            </article>
                        </div>
                    </div>
                </section>
                <div class="block"></div>
            </div>
        </div>
    </div>
    <!--==============================footer=================================-->
    <footer>
        <div class="padding">
            <div class="main">
                <div class="wrapper">
                    <div class="fleft footer-text"> Copyright &copy; <a href="#">Domain Name</a> All Rights Reserved <strong> Design by Flowers<a target="_blank" href="[email protected]"></a></strong> </div>
                    <ul class="list-services">
                        <li>Link to Us:</li>
                        <li><a class="tooltips" href="https://www.facebook.com/mamaginas.biz/"></a></li>
                        <li class="item-1"><a class="tooltips" href="#"></a></li>
                        <li class="item-2"><a class="tooltips" href="#"></a></li>
                    </ul>
                </div>
            </div>
        </div>
    </footer>
    <script type="text/javascript">Cufon.now();</script>
    (function() {
    function validEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
    }

    function validateHuman(honeypot) {
    if (honeypot) {  //if hidden form filled up
    console.log("Robot Detected!");
    return true;
    } else {
    console.log("Welcome Human!");
    }
    }

    // get all data in form and return object
    function getFormData(form) {
    var elements = form.elements;

    var fields = Object.keys(elements).filter(function(k) {
    return (elements[k].name !== "honeypot");
    }).map(function(k) {
    if(elements[k].name !== undefined) {
    return elements[k].name;
    // special case for Edge's html collection
    }else if(elements[k].length > 0){
    return elements[k].item(0).name;
    }
    }).filter(function(item, pos, self) {
    return self.indexOf(item) == pos && item;
    });

    var formData = {};
    fields.forEach(function(name){
    var element = elements[name];

    // singular form elements just have one value
    formData[name] = element.value;

    // when our element has multiple items, get their values
    if (element.length) {
    var data = [];
    for (var i = 0; i < element.length; i++) {
    var item = element.item(i);
    if (item.checked || item.selected) {
    data.push(item.value);
    }
    }
    formData[name] = data.join(', ');
    }
    });

    // add form-specific values into the data
    formData.formDataNameOrder = JSON.stringify(fields);
    formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
    formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default

    console.log(formData);
    return formData;
    }

    function handleFormSubmit(event) {  // handles form submit without any jquery
    event.preventDefault();           // we are submitting via xhr below
    var form = event.target;
    var data = getFormData(form);         // get the values submitted in the form

    /* OPTION: Remove this comment to enable SPAM prevention, see README.md
    if (validateHuman(data.honeypot)) {  //if form is filled, form will not be submitted
    return false;
    }
    */

    if( data.email && !validEmail(data.email) ) {   // if email is not valid show error
    var invalidEmail = form.querySelector(".email-invalid");
    if (invalidEmail) {
    invalidEmail.style.display = "block";
    return false;
    }
    } else {
    disableAllButtons(form);
    var url = form.action;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url);
    // xhr.withCredentials = true;
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
    console.log(xhr.status, xhr.statusText);
    console.log(xhr.responseText);
    var formElements = form.querySelector(".form-elements")
    if (formElements) {
    formElements.style.display = "none"; // hide form
    }
    var thankYouMessage = form.querySelector(".thankyou_message");
    if (thankYouMessage) {
    thankYouMessage.style.display = "block";
    }
    return;
    };
    // url encode form data for sending as post data
    var encoded = Object.keys(data).map(function(k) {
    return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
    }).join('&');
    xhr.send(encoded);
    }
    }

    function loaded() {
    console.log("Contact form submission handler loaded successfully.");
    // bind to the submit event of our form
    var forms = document.querySelectorAll("form.gform");
    for (var i = 0; i < forms.length; i++) {
    forms[i].addEventListener("submit", handleFormSubmit, false);
    }
    };
    document.addEventListener("DOMContentLoaded", loaded, false);

    function disableAllButtons(form) {
    var buttons = form.querySelectorAll("button");
    for (var i = 0; i < buttons.length; i++) {
    buttons[i].disabled = true;
    }
    }
    })();
</body>
</html>
chore duplicate invalid

Most helpful comment

@kimflow1

after your<form>tag try entering a div with the class as form-elements. This tells the script what area needs to be cleared to display the success message.

<form class="gform" data-email="[email protected]" method="post" enctype="multipart/form-data" action="https://script.google.com/macros/s/AKfycbwA99DAoedqxZzJTOzyS-2-o1EcXVkjy-X0yenXpTNIiJgUBA/exec">
<div class="form-elements">
                                            <fieldset>
                                                (all that stuff here)
                                                        </div>
                                                    </div>
                                                </div>
                                              </div>
                                            </fieldset>
                                        </form>

Also, it looks like you are trying to load that cufon script at the same time, and accidentally closed the tag before the form script

try this:

<script type="text/javascript">Cufon.now();</script>

<script type="text/javascript">

-------All that javascript here (don't copy this line)-------

</script>

All 5 comments

I made your paste into a more readable code snippet.

You are using a third party dependency which could change what is going on here. I don't know that project so it's hard to say.
https://github.com/sorccu/cufon/wiki/API

To better get assistance, I would suggest making a minimally viable example. Do you need those third party dependencies to get a proof of concept form working? It's hard to figure it out without debugging this entire thing for you, and that would require more than I have time for. If you don't know how JS works, I would advise starting to learn if you are editing webpages. Best of luck!

Also copied from the FAQs:

Why is the webpage forwarding to a bunch of text when I hit submit?
You are not properly loading the required Javascript which submits the data via AJAX, or your browser does not support AJAX. Please see Part 2 and check your console logs in case you are finding errors.

@kimflow1

after your<form>tag try entering a div with the class as form-elements. This tells the script what area needs to be cleared to display the success message.

<form class="gform" data-email="[email protected]" method="post" enctype="multipart/form-data" action="https://script.google.com/macros/s/AKfycbwA99DAoedqxZzJTOzyS-2-o1EcXVkjy-X0yenXpTNIiJgUBA/exec">
<div class="form-elements">
                                            <fieldset>
                                                (all that stuff here)
                                                        </div>
                                                    </div>
                                                </div>
                                              </div>
                                            </fieldset>
                                        </form>

Also, it looks like you are trying to load that cufon script at the same time, and accidentally closed the tag before the form script

try this:

<script type="text/javascript">Cufon.now();</script>

<script type="text/javascript">

-------All that javascript here (don't copy this line)-------

</script>

Thanks @itsblakewillis !

I loaded up the example provided by @kimflow1 , and making that fix caused the JSON response to only log in the console and not appear on the page, so this issues appears to be resolved unless we hear back otherwise.

Thank you so much for your help. The form for my contact page works great, although I still cannot get the "Thank you" message to show after I hit the submit button. I renamed the .js file and added it to the rest of my files (if that makes sense). I'm not sure if it's the placement of the thank you msg or the file.








Contact Form



action="https://script.google.com/macros/s/AKfycbzciNmdLEjdy85G2AhLsHpyyesopEWFBFDUl949DsjyyocnZiej/exec">









Message:













We would love to hear from you


Mama Gina鈥檚 will respond to your email within 24 hours, if you would
like a phone call please include your number and the best time to call.









Our Contacts



USA


8901 Marmora Road, Arlington, TX

Telephone: +1 682 360 3755

E-mail:[email protected]











































  • Link to Us:











Was this page helpful?
0 / 5 - 0 ratings

Related issues

Thank you message not working on mobile
eleosa picture eleosa  路  4Comments

Problem at gmail
vlknlvnt picture vlknlvnt  路  4Comments

Prevent the page from changing to the JSON NOT WORKING
Herbert2122 picture Herbert2122  路  4Comments

Doesn't send the e-mail to e-mail address.
onurusluca picture onurusluca  路  4Comments

NPM package out of date
mckennapsean picture mckennapsean  路  3Comments