如何让我的 php 处理一个 HTML 页面上的多个表单

How do I make my php process multiple forms that are on one HTML page

如何让我的 php 代码处理一个 HTML 页面上的 2 个表单。我不确定我是否完全了解如何让它工作。一直在寻找一种方法,但似乎我发现的错误比解决方案更多。

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    foreach ($_POST as $key => $value) {
        $value = trim($value);

        if (empty($value)) {
            exit("Empty fields are not allowed. Please go back and fill in the form properly.");
        } elseif (preg_match($exploits, $value)) {
            exit("Exploits/malicious scripting attributes aren't allowed.");
        } elseif (preg_match($profanity, $value) || preg_match($spamwords, $value)) {
            exit("That kind of language is not allowed through our form.");
        }

        $_POST[$key] = stripslashes(strip_tags($value));       
    }


    $recipient = "Contact Form <sample@sample.com>";
    $subject = "New Message from Sample name";

    $message = "Received an e-mail through your contact form: \n";
    $message .= "Name: {$_POST['name']} \n";
    $message .= "Address: {$_POST['address']}\r";
    $message .= "City: {$_POST['city']} \r"; 
    $message .= "State: {$_POST['state']} \r";
    $message .= "Zip: {$_POST['zip']} \n";
    $message .= "E-mail: {$_POST['email']} \n";
    $message .= "Phone: {$_POST['phone']} \n";
    $message .= "Message: {$_POST['message']} \n";

    $from = 'Contact Form <contact@sample.com>'; 

 // send email
    $success = mail($recipient,$subject,$message,"From: " . $from);

    if ($success) {
        echo "success";
    } else {
        echo "Sorry, there was an error and your mail was not sent. Please contact me at <a href='#'>Email</a> or call me at <a href=''>Phone number</a>.";
    }
}
?>

如果您使用 Javascript/jQuery,一种解决方案是先使用 jQuery 捕获值,然后通过 AJAX 将它们发送到您的 PHP 脚本。例如,假设您为表单中的每个值指定了一个 id(例如 id="recipient"),并且您为所有提交按钮指定了 class "submit",您可以收听提交,然后通过 POST 将值发送到 yourPHPscript.php,如下所示:

    $(".submit").on("click", function(e){
        e.preventDefault(); //prevents the normal handling of 'submit' event
        $.ajax({
            method: "POST",
            url: "yourPHPscript.php",
            data: {
                recipient: $("#recipient").val(),
                subject: $("#subject").val(),
                name: $("#name").val(),
                address: $("#address").val(),
                (etc.)
            }

            success: function(data){
                (do something with data)
            }
        });
    });