在表单提交时显示成功消息

时间:2016-06-10 09:14:27

标签: javascript php html forms submit

我想在同一页面上显示成功消息,而不是将用户重定向到.php文件。

我不希望使用AJAX& amp; jQuery和我想保持PHP文件与我的表单的HTML文件分开。

是否可以使用少量的Javascript?

这是我的代码;

HTML表单

<div id="viewing-container">
    <div id="viewing-header">
        <h3 class="form-header">Request a Viewing</h3><button type="button" id="close" class="button-primary close-form" onclick="openClose()">&#735;</button>
    </div>
    <div id="viewing-content">
        <div id="success">
            <p class="form">Thank you for contacting us. We will be in touch soon.</p>
        </div>
        <p class="form">Please text or call Alex on <a href="">0123456789</a> for fastest response or enter your contact details below and we will call you back as soon as we can.</p>
        <form action="" method="post" autocomplete="on">
            <label for="name">Name <i>&#42;</i></label><input type="text" name="name" autofocus required><br />
            <label for="number">Contact Number <i>&#42;</i></label><input type="tel" name="number" required><br />
            <label for="message">Message <i>&#42;</i></label><textarea type="textarea" name="message" rows="5" required>Please call me to arrange a viewing of one of your properties.</textarea><br />
            <div class="g-recaptcha" data-sitekey="###"></div>
                    <br />
            <button type="submit" name="contactSubmit" id="contactSubmit" class="button-primary">Send</button>
        </form>
    </div>

PHP提交代码

$name = $number = $message = "";

if(isset($_POST['contactSubmit'])){
    $name = $_POST["name"];
    $number = $_POST["number"];
    $message = $_POST["message"];


    $msg = "Name: " . $name . "\n" . "Number: " . $number "\n" . "Message:" . $message;
    $msg = wordwrap($msg,70);

    $subject = "Viewing Request";

    mail("me@mysite.co.uk", $subject, $msg)
    header("Location: /index.htm");
}

exit;

我尝试使用onclick()Javascript函数来显示成功,但是在可以显示Javascript函数之前,表单会重定向到PHP文件。我唯一能够工作的是一个javascript警报功能,但这不是很吸引人或用户友好。我想显示成功消息并运行外部php文件而不重新加载HTML页面。

请帮忙!!我不是非常精通PHP或Javascript :( 提前谢谢。

2 个答案:

答案 0 :(得分:1)

<?php
$nameErr = $numberErr = $messageErr = "";
$name = $number = $message = "";
if(isset($_POST['contactSubmit'])){
$name = $_POST["name"];
$number = $_POST["number"];
$message = $_POST["message"];
$msg = "Name:" . $name . "\n" . "Number: " . $number. "\n" . "Message:" . $message;
    $msg = wordwrap($msg,70);
$subject = "Viewing Request";
mail("me@mysite.co.uk", $subject, $msg)?>
<script>alert("your message is sent successfully");
 window.location="index.html";
</script>
<?php  } ?>

提交表单后,您会收到alert,其中包含已成功发送message的消息,如果您点击“确定”,则会redirect转到index.html。另请使用javascript window.location beacuse header会给出已发送的错误

答案 1 :(得分:1)

你可以通过使用AJAX调用来实现这一点,jQuery是你最好的朋友。

jQuery将为您节省大量代码行,非常简单易用,只需将cdn托管链接添加到您的HTML <head>

  1. form.html

    <html>    
    <head>
    
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    
    </head>
    
  2. 在html文件中将表单添加到此JS脚本之后 (您也可以使用单独的文件&#34; script.js&#34;并在jquery链接之后将其添加到头部,但我们将避免使其过于复杂。)

    <div id="viewing-container">
        <!-- your form -->
    </div>
    
    <script>
        $(document).ready(function() {
    
    // hide the success message
    $('#success').hide(); 
    
    // process the form
    $('form').submit(function(event) {
    
        // get the form data before sending via ajax
        var formData = {
            'name'               : $('input[name=name]').val(),
            'number'             : $('input[name=number]').val(),
            'message'            : $('input[name=message]').val(),
            'contactSubmit'      : 1 
        };
    
        // send the form to your PHP file (using ajax, no page reload!!)
        $.ajax({
            type: 'POST', 
            url:  'file.php', // <<<< -------  complete with your php filename (watch paths!)
            data:  formData,  // the form data
            dataType: 'json', // how data will be returned from php
            encode: true
        })
        // JS (jQuery) will do the ajax job and we "will wait that promise be DONE"
        // only after that, we´ll continue
        .done(function(data) {
            if(data.success === true) {
               // show the message!!!
               $('#success').show();
            }
            else{
                // ups, something went wrong ...
                alert('Ups!, this is embarrasing, try again please!');
                } 
            });
        // this is a trick, to avoid the form submit as normal behaviour
        event.preventDefault();
    });
        }); 
    </script>
    
  3. 最后,更改php文件的最后两行:

    <?php 
    
    // .... your code .... 
    
    //mail("me@mysite.co.uk", $subject, $msg)
    //header("Location: /index.htm");
    
    if(mail("me@mysite.co.uk", $subject, $msg)) {
        $data['success'] = true;
    }
    else{
        $data['success'] = false;
    }
    
    // convert the $data to json and echo it
    // so jQuery can grab it and understand what happend
    echo json_encode($data);
    
    ?>