我正在尝试制作PHP邮件表单。我有这样的工作:
<form method="post" action="PHP/index.php" autocomplete="off">
<fieldset class="singleLine">
<input id="name" type="text" name="name" required>
<label for="name">Full Name</label>
<div class="after"></div>
</fieldset>
<fieldset class="singleLine">
<input id="email" type="text" name="email" required>
<label for="email">Email</label>
<div class="after"></div>
</fieldset>
<fieldset class="multiLine">
<textarea onkeydown="textAreaAdjust(this)" id="message" type="textarea" name="message" required></textarea>
<label for="message" id="messageTop">Message</label>
<div class="after"></div>
</fieldset>
<fieldset>
<input id="submit" name="submit" type="submit" value="Submit">
</fielset>
</form>
这是我的PHP文件
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: ';
$to = '';
$subject = 'Contact Form';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
我不喜欢这种方法,它会将您发送到新页面,其中文本消息已发送或出错。 我真的想用弹出/模态来制作它。模态不是问题。
Ajax调用给了我一些问题。 我需要更改我的PHP代码,但不知道如何。有人可以帮助我吗?我不熟悉PHP。
这是我的ajax调用和修改后的表单
的JS代码function sendMail() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var text = $("#message").val();
var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
$.ajax({
url: 'PHP/index.php',
type: 'post',
data: dataString
})
.promise()
.done(function (data) {
alert("done");
});
});
}
形式:
<form autocomplete="off">
<fieldset class="singleLine">
<input id="name" type="text" name="name" required>
<label for="name">Full Name</label>
<div class="after"></div>
</fieldset>
<fieldset class="singleLine">
<input id="email" type="text" name="email" required>
<label for="email">Email</label>
<div class="after"></div>
</fieldset>
<fieldset class="multiLine">
<textarea onkeydown="textAreaAdjust(this)" id="message" type="textarea" name="message" required></textarea>
<label for="message" id="messageTop">Message</label>
<div class="after"></div>
</fieldset>
<fieldset>
<div id="submit" name="submit">Submit</div>
<!--<input id="submit" name="submit" type="submit" value="Submit">-->
</fielset>
</form>
答案 0 :(得分:2)
为表单提供课程或身份证明。
function sendMail() {
//bind on the submit of the form
$(".myForm").on('submit', function(e) {
e.preventDefault(); //cancel the normal form submission
$.ajax({
url: 'PHP/index.php',
method: 'post',
data: $(this).serialize(), //serialize all the inputs of the form for the ajax request
}).then(
function success() {
console.log(arguments);
//do stuff
},
function error() {
console.log(arguments);
//do stuff
}
)
});
}