Php Ajax阻止表单操作和发布表单数据
几天来,我一直在搜索示例,试图对我的简单电子邮件注册表单进行故障排除。我正在尝试在不离开或重新加载当前页面的情况下向数据库提交电子邮件。我可以将新数据插入数据库,但不能通过Ajax功能插入。我开始认为我的Ajax函数没有被调用,因为即使使用Php Ajax阻止表单操作和发布表单数据,php,ajax,forms,jquery,post,Php,Ajax,Forms,Jquery,Post,几天来,我一直在搜索示例,试图对我的简单电子邮件注册表单进行故障排除。我正在尝试在不离开或重新加载当前页面的情况下向数据库提交电子邮件。我可以将新数据插入数据库,但不能通过Ajax功能插入。我开始认为我的Ajax函数没有被调用,因为即使使用event.preventDefault()函数,我的页面被重定向到.php文件。我在下面列出了我的脚本,它当前位于HTML的部分 <script type="text/javascript"> $(document).ready(Function
event.preventDefault()代码>函数,我的页面被重定向到.php文件。我在下面列出了我的脚本,它当前位于HTML的
部分
<script type="text/javascript">
$(document).ready(Function() {
$("#submitbtn").click(function(event) {
event.preventDefault();
var form = $(this),
emailcode = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method');
/* responseMsg = $('#signup-response') */
if ( formData.length===0 ) {
function(msg){
alert('Invalid Email');
}
return false;
} else {
//send data to server
$.ajax({
url: formUrl,
type: formMethod,
data: emailcode,
success:function(data){
alert('Email Saved');
}
return false;
});
};
});
});
我很快注意到了一件事
form = $(this) //it is holding submit button, not the form
emailcode = form.serialize(),
formUrl = form.attr('action'), //there is no attribute `action` to select because form is holding submit button
formMethod = form.attr('method'); //similarly, there is no attribute method
将表单选择器更改为:
form = $('#emailForm')
尝试将中的“var form=$(this)”更改为var form=$(“#emailform”)。什么是“formData”?“formData”现在是“emailcode”。您的建议没有更改任何输出,但感谢您捕捉到我愚蠢的变量错误。我更改为form=$(“#emailform”)
。我还更改了form.attr('action')
和form.attr('method'))
分别到“collector.php”
和“post”
。结果没有更改,仍然指向.php页面,并且没有向.php文件传递任何数据。
form = $(this) //it is holding submit button, not the form
emailcode = form.serialize(),
formUrl = form.attr('action'), //there is no attribute `action` to select because form is holding submit button
formMethod = form.attr('method'); //similarly, there is no attribute method
form = $('#emailForm')