提问者:小点点

表单无法正常工作的成功消息


我正在处理位于此处通知按钮中的表单

我现在正在测试表单,我在我的电子邮件中收到了每一份提交,但是在前端,我的成功信息显示在屏幕上。

我希望此表单的工作方式与网站上的联系人表单完全相同,其中成功消息会在占位符中弹出。。或者在表单的底部

表单的html和js如下所示。我有一种感觉,好像我把课堂和/或身份证搞砸了。我得到了所有这些代码在线,并一直在编辑它,使它做什么,我需要它做LOL!现在我被卡住了

超文本标记语言

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

匿名用户

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

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

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

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

使用成功/错误函数将成功消息推送到超文本标记语言

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

匿名用户

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

第一步

序列化表单数据,将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);
        }
    }
?>

现在,我们需要从索引请求函数。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();

    }

?>