【问题标题】:PHP Forms and Ajax calls, reports undefined index error after form submitPHP Forms 和 Ajax 调用,表单提交后报告未定义索引错误
【发布时间】:2017-01-26 23:31:08
【问题描述】:

这是我第二次尝试在我的网站上建立一个有效的联系部分。在阅读了调试 php 之后,我仍然不知道下一步该做什么。点击提交后,我得到一个“未定义的索引”错误——它引用了多行作为问题。

 <?php

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    // Check that data was sent to the mailer.
    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "Oops! There was a problem with your submission. Please complete the form and try again.";
        exit;
    }

    // Set the recipient email address.
    $recipient = "someone@example.com";

    // Set the email subject.
    $subject = "New contact from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>

似乎 ajax 验证正在工作——但一旦我点击提交,就会出现错误。我也会在下面包含 HTML。

<form id="ajax-contact" method="post" action="php/mailer.php" role="form">
                  <div class="form-group">
                    <label for="name">Your Name</label>
                    <input type="text" id="name" class="form-control" required>
                  </div>
                  <div class="form-group">
                    <label for="email">Email address</label>
                    <input type="email" id="email" class="form-control" required>
                  </div>
                  <div class="form-group">
                    <label for="message">Message</label>
                    <textarea id="message" rows="5" class="form-control" required></textarea>
                  </div>
                  <button type="submit" class="btn">Submit</button>
                </form>

如果您需要更多信息,或者我需要自行调试更多信息,请告诉我。感谢您的宝贵时间!

$(function() {

// Get the form.
var form = $('#ajax-contact');

// Get the messages div.
var formMessages = $('#form-messages');

// Set up an event listener for the contact form.
$(form).submit(function(e) {
    // Stop the browser from submitting the form.
    e.preventDefault();

    // Serialize the form data.
    var formData = $(form).serialize();

    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
    })
    .done(function(response) {
        // Make sure that the formMessages div has the 'success' class.
        $(formMessages).removeClass('error');
        $(formMessages).addClass('success');

        // Set the message text.
        $(formMessages).text(response);

        // Clear the form.
        $('#name').val('');
        $('#email').val('');
        $('#message').val('');
    })
    .fail(function(data) {
        // Make sure that the formMessages div has the 'error' class.
        $(formMessages).removeClass('success');
        $(formMessages).addClass('error');

        // Set the message text.
        if (data.responseText !== '') {
            $(formMessages).text(data.responseText);
        } else {
            $(formMessages).text('Oops! An error occured and your message           could not be sent.');
        }
    });

    });

    });

我已经添加了 ajax。我第一次用更正的 HTML 测试页面时,它完全符合我的要求。但是,现在点击“提交”后,“成功”消息将显示在新页面上。

【问题讨论】:

  • 您的表单字段需要指定nameid 未在$_POST 中使用
  • 如果可能,也添加 ajax..

标签: php ajax forms phpmailer


【解决方案1】:

正如@RST 在他的评论中所说,您需要为您的输入字段提供nameid 属性仅在 DOM 中使用,用于 JS、HTML 锚点和 CSS 类。它们不会作为 POST/GET 请求的一部分发回,因此据 PHP 所知不存在。

确保将来不会出现此类错误的一个好方法是检查空(或未设置)值。如果它是必填字段,则应使用empty() 进行检查,但如果该字段可以是空字符串,则isset() 将是正确的测试方法。
又快又脏的例子:

// Test and validate the username, which is a required field.
if (empty ($_POST['username'])) {
    $errors[] = "Username must be specified";
} elseif (!filter_var ($_POST['username'], E_VALIDATE_REGEXP, '/^[A-Za-z0-9]+\\z/u')) {
    $errors[] = "Invalid username specified";
} else {
    $username = $_POST['username'];
}

// Test an optional field like a checkbox, which (if not checked)
// causes the field to be missing from the POST data.
$optional = false;
if (isset ($_POST['checkbox']) && $_POST['checkbox'] == 1) {
    $optional = true;
}

您会注意到我在上面的代码中使用了一个错误数组,如果有任何验证失败,它可以很容易地检测(和显示)。现在您只需要检查所述数组是否为空,而不是检查每个变量是否包含一个值。额外的好处是所有错误都随时可用,以便在出现问题时更轻松地向用户列出。

我还要指出一件事,那就是您对strip_tags() 的使用。这不会帮助您抵御 SQL 注入,也不会为您提供针对 XSS 攻击的充分保护。因此应避免使用它,而应采用适当的技术。比如htmlspecialchars()在向HTML输出添加东西时,或者在向数据库发送东西时准备语句。

【讨论】:

  • 感谢您的回复!我现在正在做这件事。我会回复你,让你知道进展如何!
  • 感谢您提供的所有信息!主要问题似乎在 HTML 中。我将使用您提供的示例来帮助完善我的 PHP。 :-)
  • 不客气。请记住也接受答案。 :)
  • 看来我只能算一个作为“答案”,我可以给你们两个投票一次。还有什么我可以做的吗?
  • 不,但没关系。没有看到您先接受了另一个答案,对此感到抱歉。
【解决方案2】:

两个可能的原因

  1. 表单字段中缺少name 属性
  2. AJAX 提交调用未发送数据

地址在表单字段中缺少name 属性

name 表单字段中缺少属性。我已经使用名称属性更新了您的表单字段。将您的表单更新为以下表单并检查您的 ajax 调用。

<form id="ajax-contact" method="post" action="php/mailer.php" role="form">
    <div class="form-group">
        <label for="name">Your Name</label>
        <input type="text" id="name" name="name" class="form-control" required>
    </div>
    <div class="form-group">
        <label for="email">Email address</label>
        <input type="email" id="email" name="email" class="form-control" required>
    </div>
    <div class="form-group">
        <label for="message">Message</label>
        <textarea id="message" rows="5" name="message" class="form-control" required></textarea>
    </div>
    <button type="submit" name="submit" class="btn">Submit</button>
</form>

在 ajax 调用中发送数据

在您的表单字段具有名称属性后,更新您的 ajax 调用以使用这些名称。在 ajax 请求期间,还包括如下表单字段。通过使用$('#ajax-contact').serialize(),它将所有信息发送到服务器。如果您是第一次使用 serialize,请使用它。

Ajax 调用示例

$.ajax({
    url: 'yourdomain.com/php/mailer.php',
    method: 'POST',
    data: $('#ajax-contact').serialize(),
    dataType: 'json',
    success: function() {
        // Your success callback
    },
    error: function() {
        // Your error callback
    }
});

建议

与其他建议一样,使用isset()empty() 对值进行严格检查。这是一个很好的做法。如果您在处理后仍有问题,请使用 AJAX 调用更新您的问题,我们会尽力帮助您。请让我们知道它是否对您有用。

【讨论】:

  • 感谢所有帮助!首先,我将更新 HTML 并查看它是否有效。如果是这样,我将在基本功能完成后添加 isset() 或任何其他建议。 :-)
  • 有效!收到包含提供的所有字段信息的电子邮件!我将如何在我的 php 中实现 isset() 和 empty()?我应该删除以下内容吗? "ini_set('display_errors', '开');"和“错误报告(E_ALL);” ?为了帮助调试,我将它们包含在我的 php 文件的顶部。
  • 实现isset()来检查变量是否被设置:$name = isset($_POST['name']) ? $_POST['name'] : false;
  • 好吧,在我还没来得及去 isset 之前,好像有别的东西坏了!最初,表单在更正后工作得很好——但现在点击“提交”后,它会将用户带到另一个页面......(仍然有效,但不是我想要的)
  • 好的,您可能在进行 ajax 调用之前错过了 e.preventDefault()。确保它在那里。也尝试在e.preventDefault() 之后使用e.stopImmediatePropagation()
猜你喜欢
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-15
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多