复杂的联系表格提交(ajax帮助)

时间:2015-01-30 18:25:28

标签: php ajax forms contact contact-form

如何在不重新加载或更改提交页面的情况下运行此联系表单?我被告知要使用ajax,但我不知道从哪里开始。

我希望能够在div中的index.html上显示输出('Successfully sent!Thank you。')。

<?php if (isset($_POST["contact"])){

$to  = 'contact@example.com';       //Contact Email

$from  = $_POST["email"];
$name = $_POST["name"];
$message = $_POST["message"];

// subject
$subject = 'New message from '.$name;


// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: ' .$to. "\r\n";
$headers .= 'From: '.$from . "\r\n";

// Mail it
if(mail($to, $subject, $message, $headers)){
    echo "Successfully sent! Thank you.";
} else {
    echo "Oops! Failed to send your message";
}

}

?>

1 个答案:

答案 0 :(得分:0)

尝试以下代码=)

HTML

<form id="contactform" name="contactform" method="post" action="email.php">
<div>
    <input type="text" name="name">
</div>
<div>
    <input type="email" name="email">
</div>
<div>
    <input type="text" name="subject">
</div>
<div>
    <textarea name="message"></textarea>
</div>
    <button type="submit">
        Send Message
    </button>
</form>

AJAX

var form = $('#contactform');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('<div></div>');
    $.ajax({
        type:"post",
        url: $(this).attr('action'),
        data: $(this).serialize(),
        beforeSend: function(){
            form.prepend( form_status.html('<p>Sending</p>').fadeIn() );
        }
    }).done(function(data){
        form_status.html('<p>Done</p>').delay(3000).fadeOut();
    });
});

email.php

<?php 

$to  = 'contact@example.com';       //Contact Email

$from  = $_POST["email"];
$name = $_POST["name"];
$message = $_POST["message"];

// subject
$subject = 'New message from '.$name;


// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: ' .$to. "\r\n";
$headers .= 'From: '.$from . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);

?>