简体   繁体   中英

Contact Form to Google Spreadsheet and Email

I created a contact form that Send values to the Google spreadsheet. I used the https://gist.github.com/willpatera/ee41ae374d3c9839c2d6 .

However, the client wanted to get the same information in email as well.

I combined two scripts together and on the console log I get success messages from both POST action, but for some reason email is not coming to the email.

Here is my HTML/php:

<form id="foo-page">
    <input type="text" class="form-control" name="first_name" id="first_name" aria-describedby="nameHelp" placeholder="" required>
    <input type="text" class="form-control" name="last_name" id="last_name" aria-describedby="nameHelp" placeholder="" required>
    <input type="email" name="email" class="form-control" id="email" placeholder="" required>
    <input type="tel" name="phone" class="form-control" id="phone" placeholder="" required>
    <fieldset class="form-group" role="radiogroup" aria-required="true">
        <legend>Reason</legend>
            <div class="form-check">
              <label class="form-check-label">
                <input type="radio" class="form-check-input" name="reason" id="Help voting" required="required" value="Help voting">
                <p>Help voting</p>
              </label>
            </div>
            <div class="form-check">
            <label class="form-check-label">
                <input type="radio" class="form-check-input" name="reason" id="Can't find my control number" required="required" value="Can't find my control number">
                <p>Can't find my control number</p>
              </label>
            </div>
            <div class="form-check">
            <label class="form-check-label">
                <input type="radio" class="form-check-input" name="reason" id="optionsRadios3" required="required" value="Other" >
                <p>Other</p>
              </label>
            </div>
        </fieldset>
    <input type="text" class="form-control" name="broker_name" id="broker_name" aria-describedby="nameHelp" placeholder="">
    <input type="email" name="broker_email" class="form-control" id="broker_email" placeholder="">
    <input type="text" name="institution" class="form-control" id="institution" placeholder="">
    <textarea class="form-control" id="message" name="message" rows="3" required></textarea>
    <button type="submit" class="btn_submit">Submit</button>
</form>

Here is my Javascript:

$("#foo-page").submit(function(event){
    const $form_message = $('#form_message');
    const $form_elements = $('#form_elements');
    $form_elements.fadeOut(500);
    $form_message.html('<h5>We got your information. Thank you</h5>').delay(500).fadeIn(700);
    setTimeout( () => {
        const $page_form = $('form#foo-page');
        $page_form[0].reset();
        $form_message.fadeOut(500);
        $form_elements.delay(700).fadeIn(500);
    },5000);
    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();
    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);
    // Fire off the request to /form.php
    request = $.ajax({
        url: "https://script.google.com/macros/s/AKfycby0yy7tBNjqayyepRbX7JcwDly0pkkKxD0M_oxlfL7FujB5CvM/exec",
        type: "post",
        sheet: "page",
        data: serializedData

    });
    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(response);
        console.log(textStatus);
        console.log(jqXHR);
    });
    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });
    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });
    // Prevent default posting of form
    event.preventDefault();
    if (event.isDefaultPrevented()) {
        var url = "../contactpage_form.php";
        $.ajax({
            type: "POST",
            url: url,
            data: $(this).serialize(),
            success: function (data)
            {
                // $('#foo-page').addClass('nonactive');
                var messageAlert = 'alert-' + data.type;
                var messageText = data.message;
                console.log(messageAlert+'-'+messageText);
                var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable">' + messageText + '</div>';       
            }
        });
        return false;
    }
});

And lastly my Form.php:

<?php 
    $from = 'From <....................>';
    $sendTo = '.............';
    $subject = 'New message from contact form';
    $fields = array('first_name' => 'FirstName', 'last_name' => 'LastName', 'phone' => 'Phone', 'reason' => 'Reason','email' => 'Email', 'broker_name' => 'BrokerName', 'broker_email' => 'BrokerEmail', 'institution' => 'Institution', 'message' => 'Message');
    $okMessage = 'Successful sending';
    $errorMessage = 'Didnt work';


    try{
        $emailText = "text";
        foreach ($_POST as $key => $value) {
            if (is_array($value)) {
               $emailText .= "$fields[$key]: " . implode(',', $value) . "\n";
                continue;
            }
            if (isset($fields[$key])) {
                $emailText .= "$fields[$key]: $value\n";}
            }
                mail($sendTo, $subject, $emailText, $from);
                $responseArray = array('type' => 'success', 'message' => $okMessage);
        }
    catch (\Exception $e){
        $responseArray = array('type' => 'danger', 'message' => $errorMessage);
    }
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $encoded = json_encode($responseArray);
        header('Content-Type: application/json');
        echo $encoded;
    }else {
        echo $responseArray['message'];
    }
?>

So, Im getting this on my console log

alert-success-Successful sending
google-sheet.js:113 Hooray, it worked!
google-sheet.js:114 {result: "success", row: 3}
google-sheet.js:115 success
google-sheet.js:116 {readyState: 4, getResponseHeader: ƒ, 
getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ…}

which is good because successful sending should be from the email posting section of the script but for some reason email is not coming.

您的表单操作不会转到 form.php 在表单标签中添加正确的表单操作<form action="form.php">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM