PHP表单和Ajax调用,在表单提交后报告未定义的索引错误

PHP表单和Ajax调用,在表单提交后报告未定义的索引错误,php,ajax,forms,phpmailer,Php,Ajax,Forms,Phpmailer,这是我第二次尝试在我的网站上创建一个工作联系人部分。在阅读了调试php之后,我仍然不知道下一步该做什么。在点击submit之后,我得到了一个“undefined index”错误——它引用了多行作为问题 <?php // Only process POST reqeusts. if ($_SERVER["REQUEST_METHOD"] == "POST") { // Get the form fields and remove whitespace. $name =

这是我第二次尝试在我的网站上创建一个工作联系人部分。在阅读了调试php之后,我仍然不知道下一步该做什么。在点击submit之后,我得到了一个“undefined index”错误——它引用了多行作为问题

 <?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测试页面时,它完全符合我的要求。但是,现在,在我单击“提交”后,“成功”消息将显示在新页面上。

正如@RST在his评论中所说,您需要为输入字段指定一个
名称。
id
属性仅在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;
}
您会注意到,我在上面的代码中使用了一个errors数组,这使得在验证失败时很容易检测(和显示)。现在您只需要检查所述数组的值是否为空,而不是检查每个变量是否都包含一个值。还有一个额外的好处,就是所有的错误都可以随时使用,以便在出现问题时更容易地向用户列出

还有一件事我想指出,那就是您使用的
strip\u tags()
。这不会帮助您抵御SQL注入,也不会为您提供足够的XSS攻击保护。因此,应避免使用它,而应采用适当的技术。例如,在向HTML输出添加内容时使用
htmlspecialchars()
,或者在向数据库发送内容时使用准备好的语句。

两个可能的原因
  • 表单字段中缺少
    name
    属性
  • 未从AJAX提交调用发送数据
  • 表单字段中缺少地址
    name
    属性
    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>
    
    建议
    与其他建议的方法一样,使用
    isset()
    empty()
    对值进行严格检查。这是一个很好的做法。如果您仍然有问题,请使用AJAX调用更新您的问题,我们将尽力帮助您。请让我们知道它是否适用于您。

    您的表单字段需要指定一个
    名称
    id
    不用于
    $\u POST
    添加ajax(如果可能)。感谢所有帮助!首先,我将更新HTML,看看它是否有效。如果有,我会在基本功能完成后添加isset()或任何其他建议。:-)作品已收到包含所有现场信息的电子邮件!如何在php中实现isset()和empty()?我应该删除以下内容吗?“ini设置(‘显示错误’、‘打开’);”和“错误报告(全部);”?为了帮助调试,我在php文件的顶部包含了这些变量。实现
    isset()
    来检查变量是否已设置:
    $name=isset($\u POST['name'])$_POST['name']:false嗯,在我还没来得及到达isset之前,它似乎就坏了!最初,表单在更正后工作得很好——但现在在单击“提交”后,它会将用户带到另一个页面。。。。(仍然有效,但不是我想的那样)好吧,在进行ajax调用之前,您可能错过了
    e.preventDefault()
    。确保它在那里。在
    e.preventDefault()
    之后尝试使用
    e.stopImmediatePropagation()
    。感谢您的回复!我现在正在做这个。我会再打给你,让你知道事情的进展!谢谢你提供的所有信息!主要的问题似乎在HTML中。我将使用您提供的示例来帮助完善我的PHP.:-)不客气。请记住也接受答案。:)看来我只能算一个“答案”,而且我可以给你们两个投票一次。还有什么我能做的吗?没有,但没关系。没有看到你先接受了另一个答案,对此表示抱歉。
    // 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;
    }
    
    <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({
        url: 'yourdomain.com/php/mailer.php',
        method: 'POST',
        data: $('#ajax-contact').serialize(),
        dataType: 'json',
        success: function() {
            // Your success callback
        },
        error: function() {
            // Your error callback
        }
    });