如何在不更改页面的情况下发送联系表单

时间:2015-08-29 10:55:56

标签: php css contact-form

我希望将联系表单替换为消息"您的消息已被发送!"不改变页面,如the case which I show here

这是我的代码:jsfiddle.net/g1o79t49/1 /

1 个答案:

答案 0 :(得分:0)

1°方法

在发送电子邮件时将您的php脚本重定向到联系页面,然后显示“您的邮件已被发送!”在它上面。

这是一个例子:

send_mail.php

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
           'X-Mailer: PHP/' . phpversion();

if(mail($to, $subject, $message, $headers)){
    header('Location: ./contact.php?msg_sent=true');
}else{
    header('Location: ./contact.php?msg_sent=false');
}
?>

contact.php

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>...</style>
</head>

<body>

<?php
if ($_GET[msg_sent]=='true') {
    echo "<div class="someClass">Your message has been sent!</div>";
}elseif ($_GET[msg_sent]=='false') {
    echo "<div class="someClass">An error occurred sending your message.</div>";
}else{
?>

<form method="POST" action="./send_mail.php">
...
</form>

<?php } ?>

</body>

</html>

2°方法

使用AJAX。

做这样的事情:

<form id="contactForm1" action="/your_url" method="post">
    ...
</form>

<script type="text/javascript">
    var frm = $('#contactForm1');
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                alert('Your message was sent!');
            }
        });

        ev.preventDefault();
    });
</script>