drkj41932 2018-07-24 22:54
浏览 72

表单不成功的成功消息

I am working on a form located in the notify button here

I am testing the form now and I get every submission in my email, but on the frontend my success message is showing on the screen.

I would like for this form to work exactly like the contact form on the site where the success message pops up in a placeholder.. or at the bottom of the form

the html and js for the form are below. I have a feeling like I messed up on the class and/or id somewhere. I got all of this code online and have been editing it to make it do what I need it to do LOL! now I am stuck

HTML

 <form action="php/newsletter-process.php" id="newsletter-form" method="post">

              <input type="text" class="form-control form-control-custom" tabindex="-1"
                     id="text-field-nl" name="text-field-nl">

                <!-- Input Name -->
                <div class="nl-form-group" id="name-field">
                  <label for="form-name" class="sr-only">Name</label>
                  <input type="text" class="form-control form-control-light"
                         id="form-name" name="form-name" placeholder="Name">
                </div>
                <!-- /End Input Name -->

                <!-- Input Email -->
                <div class="nl-form-group" id="email-field">
                  <label for="form-email" class="sr-only">Email</label>
                  <input type="email" class="form-control form-control-light"
                         id="form-email" name="form-email" placeholder="Email">
                </div>
                <!-- /End Input Email -->

                <!--Check Interest-->
              <div class="nl-form-group">
                <p>Which are you more interested in?</p>
                    <input type="checkbox" id="workbook" name="interest-type[]" value="Digital Workbook"/> Digital Workbook<br/>
                    <input type="checkbox" id="vclass" name="interest-type[]" value="Virtual Class Session"/>Virtual Class Session
              </div>
              <!-- /End Input Group -->

                <!-- Submit Button -->
                <div class="btn-row">
                  <div class="form-group">
                    <button type="submit" class="btn btn-light" role="button">
                      Send Message
                    </button>
                  </div>
                </div>
                <!-- /End Submit Button -->

              <!-- Message Alert -->
              <!--div id="message-newsletter" class="message-wrapper text-white message">
                <span><i class="icon icon-sm icon-arrows-slim-right-dashed"></i><label
                    class="message-text" for="email"></label></span>
              </div-->
              <div id="message-newsletter" class="message-wrapper text-white message">
                <i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
                <span class="message-text"></span>
              </div>
              <!-- /End Message Alert -->


            </form>
            <!-- /End Newsletter Form -->

JS

/*
 --------------------------------
 Ajax Contact Form
 --------------------------------
 + https://github.com/pinceladasdaweb/Ajax-Contact-Form
 + A Simple Ajax Contact Form developed in PHP with HTML5 Form validation.
 + Has a fallback in jQuery for browsers that do not support HTML5 form validation.
 + version 1.0.1
 + Copyright 2014 Pedro Rogerio
 + Licensed under the MIT license
 + https://github.com/pinceladasdaweb/Ajax-Contact-Form
 */

(function ($, window, document, undefined) {
  'use strict';

  var form = $('#newsletter-form'),
    messageContainer = $('#message-newsletter'),
    messageText = $('#message-newsletter .message-text');

  form.submit(function (e) {

    // remove the error class
    form.find('.nl-form-group').removeClass('error');
    messageContainer.removeClass('error');

    var errorAll = '';

    // get the form data
    var formData = {
      'name': $('input[name="form-name"]').val(),
      'email': $('input[name="form-email"]').val(),
      'textfield': $('input[name="text-field"]').val()

    };

    // process the form
    $.ajax({
      type: 'POST',
      url: 'php/newsletter-process.php',
      data: formData,
      dataType: 'json',
      encode: true
    }).done(function (data) {
      // handle errors
      if (!data.success) {

       if (data.errors.name) {
          $('#name-field').addClass('error');
          errorAll = data.errors.name;
        }

        if (data.errors.email) {
          $('#email-field').addClass('error');
          errorAll = errorAll + ' ' + data.errors.email;
        }

        messageContainer.addClass('error');
        messageText.html(errorAll);
      } else {
        // display success message
        messageText.html(data.confirmation);

        $('#newsletter-form .form-control').each(function () {
          $(this).fadeIn().val($(this).attr('placeholder'));
        });
      }
      });
      messageContainer.slideDown('slow', 'swing');
      setTimeout(function () {
        messageContainer.slideUp('slow', 'swing');
      }, 10000);
    }).fail(function (data) {
      // for debug
      console.log(data)
    });

    e.preventDefault();
  });
}(jQuery, window, document));

PHP

<?php
$subjectPrefix = 'App It Out Notify';
$emailTo       = 'taking this out';

$errors = array(); // array to hold validation errors
$data   = array(); // array to pass back data

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name    = stripslashes(trim($_POST['form-name']));
    $email   = stripslashes(trim($_POST['form-email']));
    $spam    = $_POST['textfield'];

    foreach($_POST['interest-type'] as $inttype) {
    $check_boxes .= $inttype." ";
    }

    if (empty($name)) {
        $errors['form-name'] = 'Name is required.';
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['form-email'] = 'Email is invalid.';
    }

    // if there are any errors in our errors array, return a success boolean or false
    if (!empty($errors)) {
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {
        $subject = "Message from $subjectPrefix";
        $body    = '
            <strong>Name: </strong>'.$name.'<br />
            <strong>Email: </strong>'.$email.'<br />
            <strong>Email: </strong>'.$check_boxes.'<br />
        ';

        $headers  = "MIME-Version: 1.1" . PHP_EOL;
        $headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
        $headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
        $headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
        $headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
        $headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
        $headers .= "Return-Path: $emailTo" . PHP_EOL;
        $headers .= "Reply-To: $email" . PHP_EOL;
        $headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
        $headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;


        if (empty($spam)) {
          mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
        }

        $data['success'] = true;
        $data['confirmation'] = 'Congratulations. Your message has been sent successfully';
    }

    // return all our data to an AJAX call
    echo json_encode($data);
}
  • 写回答

2条回答 默认 最新

  • donglv1831 2018-07-24 23:19
    关注

    Change your button type to "button" to not reload the page.

    <button type="button" class="btn btn-light" role="button">
       Send Message
    </button>
    

    Use the Ajax 'success' and 'error' properties to handle the request success/errors

    $.ajax({
        type: 'POST',
        url: '...',
        data: {...},
        datatype: 'JSON',
        success: function(data){...},
        error: function(){...},
    });
    

    Use the success/error function to push your success message into the HTML

    <div id="message-newsletter" class="message-wrapper text-white message">
      <i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
      <span class="message-text" id="messageText"></span>
    </div>
    

    JS

    document.getElementById('messageText').innerHTML = <success or error message>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?