PHP联系表单在同一页面上成功获取消息

时间:2016-11-28 12:29:54

标签: php html forms

我在不同的网站上多次问过这个问题,但没有结果。所以我们再来一次我在这篇文章中留下的代码是来自我所做的PHP联系表的代码。正如您可以在代码底部看到" Contact.php"有些代码以if($mail->send()){开头,代码中包含以下代码:header('Location: bedankt.php');。这样做的是,当用户按下发送按钮时,他被重定向到" Bedankt.php",On" bedankt.php"他看到一条消息说“#34;表格已成功发送"。我试图完成的是以下内容:用户不会被重定向到" Bedankt.php"但相反,他会在表单本身上方看到相同的消息,因此他保持在同一页面上但当他/她按下发送按钮时,表单上方会弹出一行文字说“#34;表单已成功发送& #34 ;.当然,形式必须像现在一样工作。 你们能为我提供一些代码吗?我希望我终于得到一个有效的anwser。只是为了清除,这是一张说明它的图片:enter image description here

提前谢谢。

的index.php

<?php

session_start();

require_once 'helpers/security.php';

$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>Servicepunt Detailhandel Groningen | Contact</title>
<link rel="shortcut icon" href="../../images/favicon/favicon.png" type="image/png">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css?<?php echo date('l jS \of F Y h:i:s A'); ?>"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">  </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<body>
<div class="container-fluid">
<!-- NAVIGATIE BALK -->
<nav class="navbar navbar-default" role="navigation">
<!-- logo -->
<div class="navbar-header">
  <!--  -->
  <a class="navbar-brand" href="../../index.php">
    <!-- <img src="images/logo.png" alt="" style="width: 50px; height: 60px;"> -->
  </a>

  <!-- Inklappbaar ding als je op mobiel zit-->
  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#mainnavbar">
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
</div>

<!-- menu eitems  linker kant-->
<div class="collapse navbar-collapse" id="mainnavbar">
  <ul class="nav navbar-nav navbar-right">

    <li><a href="../../index.php">Home</a></li>
    <li><a href="../Over/index.php">Over</a></li>
    <li><a href="../Nieuws/index.php">Nieuws</a></li>
    <li class="active"><a href="index.php">Contact</a></li>

    <!-- Dropdown -->
    <!--
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown">Profiel <span class="caret"></span></a>
        <ul class="dropdown-menu">
          <li><a href="#">Profiel</a></li>
          <li><a href="#">Instellingen</a></li>
        </ul>
    </li>
    -->
    <!-- <li><button type="button" class="btn btn-primary btn-lg raised">Niet beschikbaar</button></li> -->
  </ul>

</div>
  <!-- Aan de rechterkant -->

<!-- EINDE NAVIAGTIE BALK-->

</nav>

<div class="header">
<h1>contact</h1>
</div>

<div id="footer">

<div  class="col-md-3 col-md-offset-9 col-xs-5" id="contact">

<?php if(!empty($errors)): ?>
    <div class="panel">
        <ul>
            <li>
                <?php echo implode('</li><li>', $errors); ?>
            </li>
        </ul>
    </div>
<?php  endif; ?>
<form action="libs/contact.php" method="post">
    <label>
        Uw naam*
        <input type="text" name="name" id="naam" autocomplete="off" <?php echo isset($fields['naam']) ? 'Value="' . e($fields['naam']) . '"' : '' ?>>
    </label>
    <br>
    <label>
        Uw emailadres *
        <input type="email" name="email" id="email" autocomplete="off" <?php echo isset($fields['email']) ? 'Value="' . e($fields['email']) . '"' : '' ?>>
    </label>
    <br>
    <label>
        Onderwerp *
        <input type="text" name="subject" id="subject" autocomplete="off" <?php echo isset($fields['subject']) ? 'Value="' . e($fields['subject']) . '"' : '' ?>>
    </label>
    <br>
    <label>
        Uw bericht *<br>
        <textarea name="bericht" id="contact" rows="8"><?php echo isset($fields['bericht']) ? e($fields['bericht']) : '' ?></textarea>
    </label>
    <br>
    <input id="button" type="submit" value="Verzenden">

</form>


</div>

<!-- <iframe class="col-xs-6" id="google"
width="auto" height="300" frameborder="0" style="border:0"    src="https://www.google.com/maps/embed/v1/place?key=AIzaSyA5QHkZAm-DkqHj4egxMm394bB6VVu5sr8 &q=Leonard+Springerlaan+1,+9727+KB+Groningen" allowfullscreen>
</iframe> -->

</div>
</div>
</body>
</html>


<?php
unset($_SESSION['errors']);
unset($_SESSION['fields']);
?>

CONTACT.PHP

<?php

session_start();

require_once "phpmailer/PHPMailerAutoload.php";

$errors = [];

if(isset($_POST['name'], $_POST['email'], $_POST['subject'], $_POST['bericht'])) {

$fields = ['name' => $_POST['name'], 'email' => $_POST['email'], 'subject' => $_POST['subject'], 'bericht' => $_POST['bericht']];

foreach($fields as $field => $data) {
    if(empty($data)){
        $errors[] = $field . ' is verplicht!';
    }
}

if(empty($errors)){
    $mail = new PHPMailer;

    $mail->isSMTP();
    $mail->SMTPAuth = true;

    $mail->Host = 'smtp.example.com';
    $mail->Username = 'example@outlook.com';
    $mail->Password = 'example';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->isHTML();
    $mail->SMTPDebug = false;

    $mail->Subject = $fields['subject'];
    $mail->Body = '"' . $fields['name'] .'"'.' heeft uw contactformulier ingevuld op uw website met het volgende bericht: ' . '<br><br>' .'Onderwerp: ' . $fields['subject'] . '<br>' . '<br>'.$fields['bericht'];

    $mail->FromName = $fields['name'];

    $mail->AddAddress('Example@outlook.com', 'Example Person'); //added mail id of owner

    if($mail->send()){

        $mail = new PHPMailer;

        $mail->isSMTP();
        $mail->SMTPAuth = true;

        $mail->Host = 'smtp.example.com';
        $mail->Username = 'example@outlook.com';
        $mail->Password = 'example';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->isHTML();
        $mail->SMTPDebug = 2;

        $mail->Subject = 'Bevesteging contactformulier';
        $mail->Body = 'Beste ' . $fields['name'] . ',' . '<br><br>' . 'Dankuwel voor het invullen van ons contactformulier op onze site. U krijgt zo snel mogelijk
                       bericht terug van ons<br> Uw bericht was als volgt: <p>'. 'Onderwerp: ' . $fields['subject'] . '<br>' . $fields['bericht'] .'</p>';

        $mail->FromName = 'Example';

        $mail->AddAddress($fields['email'] , $fields['name']); //added mail id of user
        if($mail->send()){
            header('Location: bedankt.php');
            die();
        }
        else{
            exit;
        }
    } else {
        echo $mail->ErrorInfo; exit;
    }
}

} else {
$errors[] = 'Something went wrong.';
}

$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;

header('location: index.php');

3 个答案:

答案 0 :(得分:0)

将您的CONTACT.PHP代码添加到INDEX.php代码上方。将表单的动作URL更改为self,“#”

检查以下代码。

<?php

session_start();

require_once 'helpers/security.php';
require_once "phpmailer/PHPMailerAutoload.php";

$errors = [];
$fields = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
    if(isset($_POST['name'], $_POST['email'], $_POST['subject'], $_POST['bericht'])) {

        $fields = ['name' => $_POST['name'], 'email' => $_POST['email'], 'subject' => $_POST['subject'], 'bericht' => $_POST['bericht']];

        foreach($fields as $field => $data) {
            if(empty($data)){
                $errors[] = $field . ' is verplicht!';
            }
        }

        if(empty($errors)){
            $mail = new PHPMailer;

            $mail->isSMTP();
            $mail->SMTPAuth = true;

            $mail->Host = 'smtp.example.com';
            $mail->Username = 'example@outlook.com';
            $mail->Password = 'example';
            $mail->SMTPSecure = 'tls';
            $mail->Port = 587;

            $mail->isHTML();
            $mail->SMTPDebug = false;

            $mail->Subject = $fields['subject'];
            $mail->Body = '"' . $fields['name'] .'"'.' heeft uw contactformulier ingevuld op uw website met het volgende bericht: ' . '<br><br>' .'Onderwerp: ' . $fields['subject'] . '<br>' . '<br>'.$fields['bericht'];

            $mail->FromName = $fields['name'];

            $mail->AddAddress('Example@outlook.com', 'Example Person'); //added mail id of owner

            if($mail->send()){

                $mail = new PHPMailer;

                $mail->isSMTP();
                $mail->SMTPAuth = true;

                $mail->Host = 'smtp.example.com';
                $mail->Username = 'example@outlook.com';
                $mail->Password = 'example';
                $mail->SMTPSecure = 'tls';
                $mail->Port = 587;

                $mail->isHTML();
                $mail->SMTPDebug = 2;

                $mail->Subject = 'Bevesteging contactformulier';
                $mail->Body = 'Beste ' . $fields['name'] . ',' . '<br><br>' . 'Dankuwel voor het invullen van ons contactformulier op onze site. U krijgt zo snel mogelijk
                       bericht terug van ons<br> Uw bericht was als volgt: <p>'. 'Onderwerp: ' . $fields['subject'] . '<br>' . $fields['bericht'] .'</p>';

                $mail->FromName = 'Example';

                $mail->AddAddress($fields['email'] , $fields['name']); //added mail id of user
                if($mail->send()){
                    $errors[] = "Your Success Message";
                }
                else{
                    $errors[] = "Your failure message";
                }
            } else {
                $erros[] = $mail->ErrorInfo;
            }
        }

    } else {
        $errors[] = 'Something went wrong.';
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Servicepunt Detailhandel Groningen | Contact</title>
    <link rel="shortcut icon" href="../../images/favicon/favicon.png" type="image/png">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css?<?php echo date('l jS \of F Y h:i:s A'); ?>"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">  </script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="js/script.js"></script>
</head>
<body>
<body>
<div class="container-fluid">
    <!-- NAVIGATIE BALK -->
    <nav class="navbar navbar-default" role="navigation">
        <!-- logo -->
        <div class="navbar-header">
            <!--  -->
            <a class="navbar-brand" href="../../index.php">
                <!-- <img src="images/logo.png" alt="" style="width: 50px; height: 60px;"> -->
            </a>

            <!-- Inklappbaar ding als je op mobiel zit-->
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#mainnavbar">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>

        <!-- menu eitems  linker kant-->
        <div class="collapse navbar-collapse" id="mainnavbar">
            <ul class="nav navbar-nav navbar-right">

                <li><a href="../../index.php">Home</a></li>
                <li><a href="../Over/index.php">Over</a></li>
                <li><a href="../Nieuws/index.php">Nieuws</a></li>
                <li class="active"><a href="index.php">Contact</a></li>

                <!-- Dropdown -->
                <!--
                <li class="dropdown">
                  <a href="#" class="dropdown-toggle" data-toggle="dropdown">Profiel <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                      <li><a href="#">Profiel</a></li>
                      <li><a href="#">Instellingen</a></li>
                    </ul>
                </li>
                -->
                <!-- <li><button type="button" class="btn btn-primary btn-lg raised">Niet beschikbaar</button></li> -->
            </ul>

        </div>
        <!-- Aan de rechterkant -->

        <!-- EINDE NAVIAGTIE BALK-->

    </nav>

    <div class="header">
        <h1>contact</h1>
    </div>

    <div id="footer">

        <div  class="col-md-3 col-md-offset-9 col-xs-5" id="contact">

            <?php if(!empty($errors)): ?>
                <div class="panel">
                    <ul>
                        <li>
                            <?php echo implode('</li><li>', $errors); ?>
                        </li>
                    </ul>
                </div>
            <?php  endif; ?>
            <form action="#" method="post">
                <label>
                    Uw naam*
                    <input type="text" name="name" id="naam" autocomplete="off" <?php echo isset($fields['naam']) ? 'Value="' . e($fields['naam']) . '"' : '' ?>>
                </label>
                <br>
                <label>
                    Uw emailadres *
                    <input type="email" name="email" id="email" autocomplete="off" <?php echo isset($fields['email']) ? 'Value="' . e($fields['email']) . '"' : '' ?>>
                </label>
                <br>
                <label>
                    Onderwerp *
                    <input type="text" name="subject" id="subject" autocomplete="off" <?php echo isset($fields['subject']) ? 'Value="' . e($fields['subject']) . '"' : '' ?>>
                </label>
                <br>
                <label>
                    Uw bericht *<br>
                    <textarea name="bericht" id="contact" rows="8"><?php echo isset($fields['bericht']) ? e($fields['bericht']) : '' ?></textarea>
                </label>
                <br>
                <input id="button" type="submit" value="Verzenden">

            </form>


        </div>

        <!-- <iframe class="col-xs-6" id="google"
        width="auto" height="300" frameborder="0" style="border:0"    src="https://www.google.com/maps/embed/v1/place?key=AIzaSyA5QHkZAm-DkqHj4egxMm394bB6VVu5sr8 &q=Leonard+Springerlaan+1,+9727+KB+Groningen" allowfullscreen>
        </iframe> -->

    </div>
</div>
</body>
</html>


<?php
unset($errors);
unset($fields);
?>

编辑: 所有错误或消息都存储在$error数组中。如果有错误或信息,将会显示。

答案 1 :(得分:0)

简单地说明我在评论中添加的内容 - 重定向到与表单相同的页面,但包含要测试的查询字符串值。如果存在GET变量,则显示消息。

/* contact.php ~ instead of bedankt.php */
if( $mail->send() ){
    die( header( 'Location: index.php?mailsent=true' ) );
}


/* index.php */
$mailsent = !empty( $_GET['mailsent'] ) ? 'Your message has been sent, thankyou!' : '';

然后,在HTML正文中的某个地方

echo $mailsent;

要克服在评论中注明的页面刷新时仍显示的消息,您可以使用元刷新

在文件的HEAD sestion中(顺便说一句:这将在5s刷新〜相应地更改数字)

<?php
    if( !empty( $_GET['mailsent'] ) ){
        echo "<meta http-equiv='refresh' content='5;url=index.php' />";
    }
?>

答案 2 :(得分:0)

你必须创建一个&lt; div&gt;如果表单发送到您的contact.php,则仅显示该元素。有很多方法可以做到这一点。由于您已经在使用php会话,因此可以使用以下方法:当您的表单向contact.php提交数据时,将名为$ _SESSION ['form_submitted'](或任何您想要的)的会话变量设置为true,并在重定向到index.php,放置一个条件块,用于计算$ _SESSION ['form_submitted'] == true是否显示&lt; div&gt;相应地包含信息。同样不要忘记在&lt; div&gt;之后将$ _SESSION ['form_submitted']的值重置为false显示块。 对于错误,您可以使用相同的会话方法和“error_occurred”之类的附加密钥来评估邮件是否已成功发送。

希望有所帮助。