表单无法正常运行的成功消息

时间:2018-07-24 22:54:27

标签: javascript php html forms

我正在处理位于通知按钮here

中的表单

我现在正在测试表单,并且我的电子邮件中都包含所有提交的内容,但是在前端,我的成功消息显示在屏幕上。

我希望此表单能够像在占位符中弹出成功消息的网站上的联系表单一样工作。.或在表单底部

该表单的html和js如下。我感觉好像在某个地方弄乱了课堂和/或ID。我将所有这些代码在线获得,并且一直在对其进行编辑以使其能够执行我所需要的大声笑!现在我被困住了

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 个答案:

答案 0 :(得分:0)

将按钮类型更改为“按钮”以不重新加载页面。

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

使用Ajax的“成功”和“错误”属性来处理请求成功/错误

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

使用成功/错误功能将您的成功消息推送到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>

答案 1 :(得分:0)

您的代码有些混乱,您可以做的是:

第一步

序列化表格数据,将formData变量更改为:

var formData = $("form#newsletter-form").serialize();

还要更改ajax中的发送数据和url:

$.ajax({
    type: 'POST',
    url: 'index.php' /*Now, we are requesting the index page instead of the php page.*/,
    data: {'submission': formData},
    datatype: 'JSON',
    success: function(data){...},
    error: function(){...},
});

第二步

您可以创建如下函数,而不用编写混乱的php代码:

<?php
    class classname{
        public function funcName($formdata,$errors,$data){

            $get = explode('&',  $formdata); // explode with and

            foreach ( $get as $key => $value) {
              $valn[ substr( $value, 0 , strpos( $value, '=' ) ) ] =  substr( $value, strpos( $value, '=' ) + 1 ) ;
            }
            // access your query param

            $name    = stripslashes(trim($valn['name']));
            $email   = stripslashes(trim($valn['email']));
            $spam    = $valn['spam'];

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

现在,我们需要从index.php请求功能。因此,请将此php代码添加到您的索引页

<?php

    if (isset($_POST['submission'])) {

        header('Content-Type: application/json; charset=utf-8');
        $subjectPrefix = 'App It Out Notify';//I don't know if you need this in your php file if so you can add it.
        $emailTo       = 'taking this out';//I don't know if you need this in your php file if so you can add it.

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

        require_once('yourphppage.php');

        $conform = new classname;
        $search->funcName($_POST['data'],$errors,$data);

        die();

    }

?>