簡體   English   中英

PHP 聯系表單在提交時未在同一頁面上顯示服務器結果

[英]PHP contact form not displaying server results on same page when submitted

我有一個帶有驗證碼的聯系表格,在提交表格時一切都很好。

它會發送電子郵件,其中包含填寫在表格中的信息。

但是,提交時,服務器結果顯示在未格式化的空白頁面中。 但是服務器結果應該顯示在特定 div 內的同一頁面上。

它以前工作過,但我更新了驗證碼,它不再工作了。 並且找不到問題。 我很擅長 PHP。

我的第二個問題是:是否可以在成功提交時隱藏表單並只顯示服務器結果 div?

提前謝謝你。

弗雷德里克

帶有聯系表格的 PHP 頁面:

<?php
    // Start a session.
    session_start();

    // Include the IconCaptcha classes.
    require('IconCaptcha-PHP/src/captcha-session.class.php');
    require('IconCaptcha-PHP/src/captcha.class.php');

    use IconCaptcha\IconCaptcha;

    // Set the IconCaptcha options.
    IconCaptcha::options([
        'iconPath' => dirname(__FILE__) . '/IconCaptcha-PHP/assets/icons', // required, change path according to your installation.
        //'themes' => [
        //    'black' => [
        //        'icons' => 'light', // Which icon type should be used: light or dark.
        //        'color' => [20, 20, 20], // Array contains the icon separator border color, as RGB.
        //    ]
        //],
        'messages' => [
            'wrong_icon' => 'Mauvaise image',
            'no_selection' => 'Aucune image séléctionnée',
            'empty_form' => 'Formulaire vide',
            'invalid_id' => 'The captcha ID was invalid.',
            'form_token' => 'The form token was invalid.'
        ],
        'image' => [
            'amount' => [ // min & max can be 5 - 8
                'min' => 5,
                'max' => 8
            ],
            'rotate' => false,
            'flip' => [
                'horizontally' => false,
                'vertically' => false,
            ],
            'border' => true
        ],
        'attempts' => [
            'amount' => 5,
            'timeout' => 60 // seconds.
        ],
        'token' => true
    ]);
    
    // If the form has been submitted, validate the captcha.
    if(!empty($_POST)) {
        if(IconCaptcha::validateSubmission($_POST)) {
            // Captcha submission was valid.
        } else {
            // Captcha submission was not valid.
        }
    }
?>

<!doctype html>


<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]>      <html class="no-js"> <![endif]-->

        <!--FORMAT-->
        <html lang="fr" xml:lang="fr" xmlns="http://www.w3.org/1999/xhtml"><head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta charset="UTF-8">
        <meta content="width=device-width, initial-scale=1.0" name="viewport">

    
        <!-- Bootstrap 4.3.1 CSS -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    
        <!-- Feuilles de style -->
        <link href="css/style.css" rel="stylesheet" />
            
        <!-- Normalize -->
        <link href="css/normalize.css" rel="stylesheet" />
            
        <!-- IconCaptcha -->
        <link href="IconCaptcha-PHP/assets/css/icon-captcha.min.css" rel="stylesheet" type="text/css">
        <script src="IconCaptcha-PHP/assets/js/icon-captcha.min.js" type="text/javascript"></script>
            
    </head> 
                        
    <body>
        
        
        <section id="contact" class="contacter">
            <div class="subcontent">
                            <div class="sous-titres-txt" style="text-align: center;">
                <br><br><h1>Modèle de formulaire de contact</h1><br><br>
            </div>
            <div class="" style="width: 90%; text-align: center; margin:0px auto;">
             <div class="form-group center-block" style="text-align: center; align-content: center">   
<!-- DEBUT FORMULAIRE CONTACT -->
                     <?php
                    if(isset($captchaMessage)) {
                        echo '<b>Captcha Message: </b>' . $captchaMessage;
                    }
                ?>
                    <form id="reused_form" role="form" method="post" action="envoiformulaire.php" style="font-family: 'Montserrat-ExtraLight'">
                            <div class="row">
                                <div class="col-md-6 form-group">
                                        <label for="first_name"></label>
                                        <input id="firstname" name="first_name" type="text" class="form-control" placeholder="Prénom">
                                </div>
                                <div class="col-md-6 form-group">
                                        <label for="last_name"></label>
                                        <input id="lastname" name="last_name" type="text" class="form-control" placeholder="NOM">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 form-group">
                                        <label for="email"></label>
                                        <input id="email" name="email" type="email" class="form-control" placeholder="Courriel">
                                </div>
                                <div class="col-md-6 form-group">
                                        <label for="telephone"></label>
                                        <input id="telephone" type="tel" name="telephone" onkeyup="formatte(this,2)" onkeypress="return isNumberKey(event)" class="form-control" placeholder="Téléphone" minlength="14" maxlength="14">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12 form-group">
                                        <label for="comments"></label>
                                        <textarea id="message" name="comments" class="form-control" placeholder="Message (400 caractères maximum)" rows="4" required="required"></textarea>
                                </div>
                                <div class="col-md-12 form-group" style="padding-top: 20px">
                                      <!-- Additional security token to prevent CSRF. Optional but highly recommended - disable via IconCaptcha options. -->
    <input type="hidden" name="_iconcaptcha-token" value="<?= IconCaptcha::token() ?>"/>

    <!-- The IconCaptcha will be rendered in this element -->
    <div class="iconcaptcha-holder" data-theme="light"></div>
                                </div>
                                <div class="col-md-12 form-group">
                                   <br> <input type="submit" id="btnContactUs" class="btn" value="Envoyer le message">
                                </div>
                            </div> <br>
 <div id="server-results" style="border-radius: 5px; background-color: #005C7B; color: #fff; font-family: 'Montserrat-ExtraLight'";><!-- FEEDBACKS du formulaire --></div>
                    </form>
                    
        <!-- Initialize IconCaptcha -->
<script type="text/javascript">
    
    // Plain JavaScript implementation.
    document.addEventListener('DOMContentLoaded', function() {
        IconCaptcha.init('.iconcaptcha-holder', {
            general: {
                validationPath: 'IconCaptcha-PHP/src/captcha-request.php', // required, change path according to your installation.
                fontFamily: 'Montserrat-ExtraLight',
                credits: 'show',
            },
            security: {
                clickDelay: 500,
                hoverDetection: true,
                enableInitialMessage: true,
                initializeDelay: 500,
                selectionResetDelay: 3000,
                loadingAnimationDelay: 1000,
                invalidateTime: 1000 * 60 * 2, // 2 minutes, in milliseconds
            },
            messages: {
                initialization: {
                    verify: 'Vérification anti-spam (cliquer).',
                    loading: 'Chargement du jeu...'
                },
                header: "Sélectionner l'image <b>la moins souvent</b> affichée",
                correct: 'Anti-spam validé',
                incorrect: {
                    title: 'Oh non, quelle horreur.',
                    subtitle: "Vous avez choisi la mauvaise image."
                },
                timeout: {
                    title: "Merci d'attendre 60 secondes.",
                    subtitle: "Trop d'échecs successifs."
                }
            }
        });
    });

</script>
        <script>
        $("#reused_form").submit(function(event){
    event.preventDefault(); //prevent default action 
    var post_url = $(this).attr("action"); //get form action url
    var request_method = $(this).attr("method"); //get form GET/POST method
    var form_data = $(this).serialize(); //Encode form elements for submission
    
    $.ajax({
        url : post_url,
        type: request_method,
        data : form_data
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});// JavaScript Document
        </script>
<!-- FIN FORMULAIRE CONTACT -->
          </div>
            </div>                      

             </div>
        </section>
        
                

        <!-- SCRIPTS -->
        
        <!-- jQuery 3.3.1 -->
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            
        <!-- Bootstrap 4.3.1 JS -->
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
        
        <!-- DIVERS -->
        <script src="js/format_tel.js"></script>
        <script src="js/isNumberKey.js"></script>
        

    </body>
</html>

PHP 進程檢查和驗證表單,並發送電子郵件:

<?php

session_start();

header('Content-Type: text/html; charset=utf-8');

require('IconCaptcha-PHP/src/captcha-session.class.php');
require('IconCaptcha-PHP/src/captcha.class.php');

use IconCaptcha\IconCaptcha;

if(isset($_POST['email'])) {

    function died($error) {
        echo " <br>Oh, quelle horreur ! <br>";
        echo $error."<br /><br />";
        die();
    }

    // Validate the captcha.
    if(!IconCaptcha::validateSubmission($_POST)) {
        died('CAPTCHA non validé!');
        // died('CAPTCHA non validé! - ' . IconCaptcha::getErrorMessage());
    }

    // validation expected data exists
    if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['comments'])) {
        died('Oups ! Un problème est survenu avec votre formulaire. Veuillez recommencer');
    }

    $first_name = $_POST['first_name']; // requis
    $last_name = $_POST['last_name']; // requis
    $email_from = $_POST['email']; // requis
    $telephone = $_POST['telephone']; // requis
    $comments = $_POST['comments']; // required

    $error_message = "";

    $email_exp ='/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; // vérifier absence de caractères interdits

    if(!preg_match($email_exp,$email_from)) {
        $error_message .= 'Le courriel saisi ne semble pas valide.<br />';
    }
    $phone_exp = "/^\d{2}\s\d{2}\s\d{2}\s\d{2}\s\d{2}/"; // de la forme XX XX XX XX XX avec 14 caractères

    if(!preg_match( $phone_exp,$telephone)) {
        $error_message .= 'Le numéro de téléphone saisi ne semble pas valide.<br />';
    }

    $string_exp = "/^[A-Za-z àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ.'-]+$/"; // lettres uniquement avec accents

    if(!preg_match($string_exp,$first_name)) {
        $error_message .= 'Le prénom saisi ne semble pas valide.<br />';
    }

    if(!preg_match($string_exp,$last_name)) {
        $error_message .= 'Le nom saisi ne semble pas valide.<br />';
    }

    if(strlen($comments) < 2) { // message en dessous de 2 caractères
        $error_message .= 'Le message saisi ne semble pas valide.<br />';
    }

    if(strlen($error_message) > 0) {
        died($error_message);
    }

    if(strlen($error_message) < 1)  {
        echo " <br>Le message a bien été envoyé, merci ! <br> <br> ";
    }

    $email_message = "Ci-après le formulaire complété.\n\n";

    function clean_string($string) {
        $bad = array("content-type","bcc:","to:","cc:","href");
        return str_replace($bad,"",$string);
    }

    $email_message .= "Prénom: ".clean_string($first_name)."\n";
    $email_message .= "NOM: ".clean_string($last_name)."\n";
    $email_message .= "Courriel: ".clean_string($email_from)."\n";
    $email_message .= "Téléphone: ".clean_string($telephone)."\n";
    $email_message .= "Message: ".clean_string($comments)."\n";

    $email_to = « coucou@coucou.com;
    $email_subject = "Nouveau message web";

    // create email headers
    $headers = 'From: '.$email_from."\r\n".
        'Reply-To: '.$email_from."\r\n" .
        'Content-Type: text/plain; charset="utf-8"'.
        'X-Mailer: PHP/' . phpversion();

    @mail($email_to, $email_subject, $email_message, $headers);
}

我嘗試使用以下代碼更改 Ajax 響應,但我仍然讓服務器結果顯示為空白頁,而不是在特定 div 中相同

 <script> $("#reused_form").submit(function(event) { event.preventDefault(); //prevent default action let post_url = $(this).attr("action"); //get form action url let form_data = $(this).serialize(); //Encode form elements for submission $.post(post_url, form_data, function(response) { $("#server-results").html(response); }); }); </script>

我還是不知道問題出在哪里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM