Search code examples
phpformsmultiple-forms

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


How can I make my php code process 2 forms that are on one HTML page. I am not sure I am quite understanding of how to get it to work. Been looking for a way but seems I keep finding more errors then solutions.

<?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>.";
    }
}
?>

Solution

  • If you are using Javascript/jQuery, one solution is to capture the values with jQuery first, then send them to your PHP script via AJAX. For example, assuming you give an id to each of your values in your forms (e.g. id="recipient"), and you give all your submit buttons the class "submit", you can listen in to a submit, and send the values via POST to yourPHPscript.php like this:

        $(".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)
                }
            });
        });