gpt4 book ai didi

php - AJAX 不调用 PHP 文件

转载 作者:行者123 更新时间:2023-12-01 07:03:18 26 4
gpt4 key购买 nike

我有一个联系我们表单,我正在尝试通过 AJAX 和 PHP 将表单数据发送到电子邮件地址。提交功能已成功触发,我收到 alert("success!"); 。然而似乎form-process.php文件从未执行 - 我从未收到 echo "I have got this far";我当然没有收到电子邮件。我哪里出错了?

有关信息,我有一个暂存站点设置,因此文件已托管在服务器上。

HTML

<div class="modal" id="contactModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Contact Us</h4>
<button type="button" class="close" data-dismiss="modal">&times;</button>
</div>

<div class="modal-body">
<form action="form-process.php" method="POST" id="contact-form" role="form">
<div class="form-group">
<input type="text" class="form-control my-2" name="name" placeholder="Full Name" />
<input type="email" class="form-control my-2" name="email" placeholder="Email Address" />
<textarea type="text" class="form-control my-2" name="message" rows="4" name="message" placeholder="Write your message here..."></textarea>
</div>
<input type="submit" name="submit" value="Submit" id="submit" class="btn btn-primary" form="contact-form"></input>
</form>
</div>

<div class="modal-footer">
</div>
</div>
</div>
</div>

JQUERY

$(document).ready(function() {
$('#contact-form').submit(function(event) {
console.log('this has fired');

var formData = {
'name' : $('input[id=name]').val(),
'email' : $('input[id=email]').val(),
'message' : $('input[id=message]').val()
};

event.preventDefault();
$.ajax({
type: "POST",
url: "form-process.php",
data: formData,
success: function(msg){
$("#contact-modal").modal('hide');
alert("success!");
},
error: function(){
alert("form post failed");
}
});
});
});

PHP

<?php
$myemail = '<myemailaddress>';
if (isset($_POST['name'])) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$company = strip_tags($_POST['company']);

echo "I have got this far";

$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Company \n $company";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
}
?>

最佳答案

您使用以下方法来获取输入字段的值:

$('input[id=name]').val(),
$('input[id=email]').val(),
$('input[id=message]').val()

但是您的输入都没有 id 字段:

<input type="text" class="form-control my-2" name="name" placeholder="Full Name" />
<input type="email" class="form-control my-2" name="email" placeholder="Email Address" />
<textarea type="text" class="form-control my-2" name="message" rows="4" name="message" placeholder="Write your message here..."></textarea>
</div>

因此您可以使用它来获取这些值:

$(input[name="name"]).val();
$(input[name="email"]).val();
$(input[name="message"]).val();

关于php - AJAX 不调用 PHP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61124347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com