我试图使用AJAX使用PHP代码将表单数据提交到.TXT文件
结果将添加到文本文件中,但AJAX功能无法正常工作。
请告诉我代码中的错误。
以下是表单的代码:
<div id="page-wrapper">
<h1>AJAX Sign Up Form </h1>
<div id="form-messages"></div>
<form id="signup" method="post" action="mailer.php">
<div class="field">
<input type="email" id="email" name="email" placeholder="Enter Your Email" required>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
这是jquery(2.1.1)代码
$(document).ready(function() {
$("#sign_btn").click(function(event){
var mail = $("#mail").val();
$.ajax({
type: "POST", // HTTP method POST or GET
url: "mailer.php", //Where to make Ajax calls
data: mail
})
.done (function(data) { $('#form-messages').html(data) })
.fail (function() { $('#form-messages').append("Opps!An Error Occured.Try Again</p>")});
});
});
这是mailer.php
<?php
$email = $_POST["email"];
$fp = fopen("signup.txt", "a");
$savestring = "$email\n";
fwrite($fp, $savestring);
fclose($fp);
echo "<h1>Thank You For Subscribing</h1>";
?>
答案 0 :(得分:2)
而不是
data: mail
使用
data: {email: mail}
因为,在PHP中,您正在寻找$_POST["email"]
,这意味着,$_POST
数组有一个名为email
且具有一定价值的键。
答案 1 :(得分:0)
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
在我的代码中将您的数据(作为对象)发送到上方 感谢
答案 2 :(得分:0)
您可以选择以下任何一项:
仅当邮件是具有
形式的所有输入的对象时 var mail = new FormData($(this)[0]);
//表格提交课程
$.ajax({
type: "POST", // HTTP method POST or GET
url: "mailer.php", //Where to make Ajax calls
data: mail
})
.done (function(data) { $('#form-messages').html(data) })
.fail (function() { $('#form-messages').append("Opps!An Error Occured.Try Again</p>")});
如果你想通过ajax将一个变量发送到php然后给它的数据键,这样你就可以通过php中的那个键来访问它了
$.ajax({
type: "POST", // HTTP method POST or GET
url: "mailer.php", //Where to make Ajax calls
data: "mail=" + mail,
})
.done (function(data) { $('#form-messages').html(data) })
.fail (function() { $('#form-messages').append("Opps!An Error Occured.Try Again</p>")});
答案 3 :(得分:0)
表单代码中缺少按钮ID ...