PHP Ajax 表单提交
PHP Ajax 表单提交
我有以下代码用于我的表单:
这是我的JS代码:
$('#updatepagebtn').click(function() { $(this).preventDefault(); $.ajax({ type:"post", url:"process/editpage.php", data: $("#editpageform").serialize(), success: function(response){ $(".result").html(response); } }); });
这是我的process/editpage.php
代码:
prepare("UPDATE content SET title=:title, description=:desc, body=:body, status=:status, slug=:url, menutitle=:menutitle, menu=:menu WHERE id=:id"); $updatepage->bindParam(':title', $_POST["title"]); $updatepage->bindParam(':desc', $_POST["description"]); $updatepage->bindParam(':body', $_POST["body"]); $updatepage->bindParam(':status', $_POST["status"]); $updatepage->bindParam(':menutitle', $_POST["menutitle"]); $updatepage->bindParam(':menu', $_POST["menu"]); $updatepage->bindParam(':id', $_POST["id"]); $url = "/".$_POST["url"]; $updatepage->bindParam(':url', $url); if($updatepage->execute()){ echo "成功!"; }else{ echo "更新页面时出错。请确保您输入了一个有效且唯一的URL。"; } }else{ echo "错误"; }
然而,当我提交表单时,它似乎只是重新加载而不是提交表单和更新表格。我尝试在表单中添加action="process/editpage.php
,然后它就正常工作了,所以我认为问题出在jQuery上,但我不确定是什么问题。
有人能看出问题并告诉我是什么问题,以便我可以解决吗?
谢谢
PHP Ajax表单提交的问题通常出现的原因是由于代码中缺少必要的事件处理和阻止默认行为的操作。解决方法可以通过将jQuery代码包裹在$(document).ready()函数中,同时将代码中的preventDefault()方法更改为e.preventDefault()。
以下是解决问题的代码示例:
$(document).ready(function() { $('#updatepagebtn').click(function(e) { $.ajax({ type: "post", url: "process/editpage.php", data: $("#editpageform").serialize(), success: function(response) { $(".result").html(response); } }); e.preventDefault(); }); });
另一种解决方法是将代码修改为:
$(document).ready(function() { $('#editpageform').submit(function(e) { $.ajax({ type: "post", url: "process/editpage.php", data: $("#editpageform").serialize(), success: function(response) { $(".result").html(response); } }); e.preventDefault(); }); });
通过以上修改,可以确保在文档加载完成后执行代码,并在点击按钮或提交表单时阻止默认行为,从而实现PHP Ajax表单的正常提交。