提交联系人表单而不刷新网页


Submiting a contact form without refreshing the webpage

这是我的代码,我在我的网站上使用。我有一个单页网站。当我点击提交按钮时,整个页面都会刷新。

请帮我解决这个问题。如需参考,请访问http://www.creativemacky.com

<?php
    $to      = 'my email';
    $email   = $_POST['email'];
    $name  = $_POST['name'];
    $message = $_POST['text-massage'];
    $headers = 'From: http://www.creativemacky.com'. '<'.$email.'>' . "'r'n" .
        'Reply-To: '. $email . "'r'n" .
        'X-Mailer: PHP/' . phpversion();
    if (mail($to, $subject, $message, $headers)){
     echo "<script>window.location.href = 'http://www.creativemacky.com';</script>";
    }
?>
<form class="_form-inline row" id="contact-form" name="contact" method="post" action="contact.php">
                                    <div class="form-group custom-form-group col-sm-6">
                                        <label class="sr-only" for="name" id="name"><span class="required">*</span>Name</label>
                                        <input type="text" class="form-control custom-form-control wow bounceInLeft animated" name="name" id="name" placeholder="Enter your name" required>
                                    </div>
                                    <div class="form-group custom-form-group col-sm-6">
                                        <label class="sr-only" for="email" id="email"><span class="required">*</span>Email</label>
                                        <input type="email" class="form-control custom-form-control wow bounceInRight animated" id="email" name="email" placeholder="Enter your email" required>
                                    </div>
                                    <div class="form-group custom-form-group col-sm-12">
                                        <label class="sr-only" for="text-massage"><span class="required">*</span>Massage</label>
                                        <textarea  class="form-control custom-form-control wow bounceInUp animated" id="text-massage" name="text-massage" rows="3" placeholder="Write something" required></textarea>
                                    </div>
                                    <button type="submit" class="pull-right btn btn-default submit-button custom-white wow bounceInLeft animated" id="submit" name="submit" value="Send">Say Hello</button>
                                </form>

您需要将php从页面中分离出来,以便在不刷新的情况下提交php ajax表单提交,这应该有助于您在不刷新页面的情况下提交。

通常要将表单数据发送到服务器而不需要刷新,您需要使用JavaScript。在JavaScript中,捕获"提交"事件并使用AJAX将数据发送到服务器。这很容易使用jQuery。

<script>
    $( "#contact-form" ).submit(function( event ) {
        var data = {
            name: $('#name').val(),
            email: $('#email').val(),
            textMessage: $('#text-message').val()
        }
        $.post('contact.php', data);
        event.preventDefault();
    });
</script>