简体   繁体   中英

PHP how to display message on same page after submitting form

I am trying to make a form that sends inserted data via email. I found this form online. This does work but I want it to display a message within the same html page (something like using innerhtml function) instead of displaying a message from a new html page.

The code is as below:

I can't figure out which function makes it move to a new page. Very new to php :(

<form name="contactform" method="post" action="php/email.php">
    This is used to call the email form php.
    <?php
    if(isset($_POST['email'])) {
        // EDIT THE 2 LINES BELOW AS REQUIRED
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $email_to = "example@example.com";
        $email_subject = "New message from ".$first_name." ".$last_name."";
        function died($error) {
            // your error code can go here
            echo "We are very sorry, but there were error(s) found with the form you submitted. ";
            echo "These errors appear below.<br /><br />";
            echo $error."<br /><br />";
            echo "Please go back and fix these errors.<br /><br />";
            die();
        }
        // validation expected data exists
        if(!isset($_POST['first_name']) ||
           !isset($_POST['last_name']) ||
           !isset($_POST['email']) ||
           !isset($_POST['phone']) ||
           !isset($_POST['message'])) {
            died('We are sorry, but there appears to be a problem with the form you submitted.');       
        }
        $first_name = $_POST['first_name']; // required
        $last_name = $_POST['last_name']; // required
        $email_from = $_POST['email']; // required
        $phone = $_POST['phone']; // not required
        $message = $_POST['message']; // required
        $error_message = "";
        $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
        if(!preg_match($email_exp,$email_from)) {
            $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
        }
        $string_exp = "/^[A-Za-z .'-]+$/";
        if(!preg_match($string_exp,$first_name)) {
            $error_message .= 'The First Name you entered does not appear to be valid.<br />';
        }
        if(!preg_match($string_exp,$last_name)) {
            $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
        }
        if(strlen($message) < 2) {
            $error_message .= 'The message you entered do not appear to be valid.<br />';
        }
        if(strlen($error_message) > 0) {
            died($error_message);
        }
        $email_message = "Form details below.\n\n";
        function clean_string($string) {
            $bad = array("content-type","bcc:","to:","cc:","href");
            return str_replace($bad,"",$string);
        }
        $email_message .= "First Name: ".clean_string($first_name)."\n";
        $email_message .= "Last Name: ".clean_string($last_name)."\n";
        $email_message .= "Email: ".clean_string($email_from)."\n";
        $email_message .= "Phone: ".clean_string($phone)."\n";
        $email_message .= "Message: ".clean_string($message)."\n";
        // create email headers
        $headers = 'From: '.$email_from."\r\n".
            'Reply-To: '.$email_from."\r\n" .
            'X-Mailer: PHP/' . phpversion();
        @mail($email_to, $email_subject, $email_message, $headers);  
        ?>
        <!-- include your own success html here -->
        Thank you for contacting us. We will be in touch with you very soon.
        <?php
    }
    ?>
</form>

I would use PHP Sessions in order to display your messages. Try it in the following manner:

Your form:

<?php
// file name: form.php

session_start();
if(!empty($_SESSION)){
    echo $_SESSION["message"];
    session_unset();
}
?>
<form action="send.php" method="post">
    <input type="text" name="first_name">
    <input type="submit">
</form>

Your email process:

<?php
// file name: send.php

session_start();

// send mail code goes here

$_SESSION["message"] = "Thanks " . $_POST["first_name"] . ". Your email has been sent!";

header("Location: form.php");

You can use a HTTP Header to redirect the user after form has been submitted.

<?php

// add this line at the end of
// your email script, change url to where
// you want to send the user
header("Location: /someWebpageHere.php");
?>

You can add another one in your died function to send the user to a Email Error Page if you wish.

You can use ajax to validate the form and show inline messages.

<!DOCTYPE html>
<html>
    <head>
        <link href="style.css" rel="stylesheet" type="text/css">
        <script src="script.js"></script>
    </head>
<body>
    <div id="mainform">
        <div class="innerdiv">
            <!-- Required Div Starts Here -->
            <h2>Form Validation Using AJAX</h2>
            <form action='#' id="myForm" method='post' name="myForm">
                <h3>Fill Your Information!</h3>
                <table>
                    <tr>
                        <td>Username</td>
                        <td><input id='username1' name='username' onblur="validate('username', this.value)" type='text'></td>
                        <td>
                            <div id='username'></div>
                        </td>
                    </tr>
                    <tr>
                        <td>Password</td>
                        <td><input id='password1' name='password' onblur="validate('password', this.value)" type='password'></td>
                        <td>
                            <div id='password'></div>
                        </td>
                    </tr>
                    <tr>
                        <td>Email</td>
                        <td><input id='email1' name='email' onblur="validate('email', this.value)" type='text'></td>
                        <td>
                            <div id='email'></div>
                        </td>
                    </tr>
                    <tr>
                        <td>website</td>
                        <td><input id='website1' name='website' onblur="validate('website', this.value)" type='text'></td>
                        <td>
                            <div id='website'></div>
                        </td>
                    </tr>
                </table>
                <input onclick="checkForm()" type='button' value='Submit'>
            </form>
        </div>
    </body>
</html>

PHP File: validation.php

<?php
$value = $_GET['query'];
$formfield = $_GET['field'];
// Check Valid or Invalid user name when user enters user name in username input field.
if ($formfield == "username") {
    if (strlen($value) < 4) {
        echo "Must be 3+ letters";
    } else {
        echo "<span>Valid</span>";
    }
}
// Check Valid or Invalid password when user enters password in password input field.
if ($formfield == "password") {
    if (strlen($value) < 6) {
        echo "Password too short";
    } else {
        echo "<span>Strong</span>";
    }
}
// Check Valid or Invalid email when user enters email in email input field.
if ($formfield == "email") {
    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $value)) {
        echo "Invalid email";
    } else {
        echo "<span>Valid</span>";
    }
}
// Check Valid or Invalid website address when user enters website address in website input field.
if ($formfield == "website") {
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $value)) {
        echo "Invalid website";
    } else {
        echo "<span>Valid</span>";
    }
}
?>

JAVASCRIPT File: script.js

javascript file with ajax functionality.

function checkForm() {
    // Fetching values from all input fields and storing them in variables.
    var name = document.getElementById("username1").value;
    var password = document.getElementById("password1").value;
    var email = document.getElementById("email1").value;
    var website = document.getElementById("website1").value;

    //Check input Fields Should not be blanks.
    if (name == '' || password == '' || email == '' || website == '') {
        alert("Fill All Fields");
    } else {
        //Notifying error fields
        var username1 = document.getElementById("username");
        var password1 = document.getElementById("password");
        var email1 = document.getElementById("email");
        var website1 = document.getElementById("website");
        //Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
        if (username1.innerHTML == 'Must be 3+ letters' || password1.innerHTML == 'Password too short' || email1.innerHTML == 'Invalid email' || website1.innerHTML == 'Invalid website') {
            alert("Fill Valid Information");
        } else {
            //Submit Form When All values are valid.
            document.getElementById("myForm").submit();
        }
    }
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
    var xmlhttp;
    if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
            document.getElementById(field).innerHTML = "Validating..";
        } else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById(field).innerHTML = xmlhttp.responseText;
        } else {
            document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
        }
    }
    xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
    xmlhttp.send();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM