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

时间:2017-03-02 22:32:29

标签: php forms multiple-forms

如何让我的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>.";
    }
}
?>

1 个答案:

答案 0 :(得分:0)

如果您使用的是Javascript / jQuery,一种解决方案是首先使用jQuery捕获值,然后通过AJAX将它们发送到PHP脚本。例如,假设您为表单中的每个值(例如id =&#34;收件人&#34;)提供了一个id,并且您将所有提交的按钮提供给班级&#34;提交&#34;,您可以听取提交,并通过POST将值发送到你的PHPscript.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)
            }
        });
    });