当我发送表单时,我不断收到两封电子邮件,而且它一直在收到#34;发送消息时出错#34;即使在我发送和接收电子邮件之后..如果字段为空,我还想显示错误消息
<?php
#if you also need this script to respond to other domains, add those header lines
// header("Access-Control-Allow-Origin: *");
// header("Access-Control-Allow-Methods: GET, POST");
// header("Access-Control-Allow-Headers: *");
if($_POST) {
$userEmail=$_POST['userEmail'];
$subject=$_POST['subject'];
//$destEmail=$_POST['destEmail'];
$body=$_POST['textarea'];
$response = mail("email@yahoo.com", $subject, $body, "From:" . $userEmail);
echo $response;
exit();
}
?>
<form >
<div data-role="fieldcontain">
<label for="subject">Subject:</label>
<input name="subject" id="Subject_input" value="" type="text">
</div>
<div data-role="fieldcontain">
<label for="email">Email:</label>
<input name="email" id="Email_input" value="" type="email">
</div>
<div data-role="fieldcontain">
<label for="textarea">
Qusstions/Feedback:
</label>
<textarea cols="40" rows="8" name="textarea" id="MessageText_input"></textarea>
</div>
<input type="button" id="sendlink" class="reset" value="submit contact"/>
</form>
<script>
$('#sendlink').on("vclick", function(e) {
"use strict";
e.preventDefault();
var data={
userEmail: $('#Email_input').val(),
subject: $('#Subject_input').val(),
textarea: $('#MessageText_input').val()
};
function sendToServer() {
return $.ajax({
url: 'yates-contact-form-app.php',
type: "POST",
dataType: "xml",
data: data
});
}
//sendToServer().done(handleSuccess);
//sendToServer().fail(handleError);
sendToServer().done(function() {
alert("Message successfully sent");
$(".reset").closest('form').find("input[type=text],input[type=email],textarea").val("");
$.mobile.navigate("#benefits-facts");
});
sendToServer().fail(function() {
alert(" Error when sending the message");
/*console.log("Error when sending the message : ");
console.log(data);
console.log(data.response);
console.log(textStatus);
console.log(jqXHR);*/
});
});
</script>
答案 0 :(得分:0)
问题是你正在调用sendToServer 2次,1为完成处理程序调用另一个失败处理程序,所以你收到邮件2次。
相反,您需要将这些处理程序注册到相同的承诺,如
$('#sendlink').on("vclick", function (e) {
"use strict";
e.preventDefault();
var data = {
userEmail: $('#Email_input').val(),
subject: $('#Subject_input').val(),
textarea: $('#MessageText_input').val()
};
//validation
if (!data.userEmail || !data.subject || !data.textarea) {
alert('enter the data!!!')
return;
}
function sendToServer() {
return $.ajax({
url: 'yates-contact-form-app.php',
type: "POST",
dataType: "xml",
data: data
});
}
var req = sendToServer();
req.done(function () {
//do your stuff
});
req.fail(function () {
//do your stuff
});
//or you can just chain both these calls
});