[英]Submitting a form without refreshing the page
I'm having a problem with jQuery(or maybe php). 我对jQuery(或php)有疑问。 I want forms to be submitted without refreshing the page so i ended up with the following code but the problem is it doesn't work.
我希望提交表单而不刷新页面,所以我最终获得了以下代码,但问题是它不起作用。 Here's the code:
这是代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#submit").click(function() {
var name = $("#name").val();
var dataString = 'name='+ name;
$.ajax({
type: "POST",
url: "p.php",
data: dataString,
success: function(){
alert("It works");
}
});
return false;
});
</script>
</head>
<body>
<form id="myForm" name="myForm" action="">
<p>
<label for="name"></label>
<input type="text" name="name" id="name" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit" />
</p>
</form>
<br />
</body>
</html>
Processing Page: 处理页面:
<?php include("../includes/includes.php"); ?>
<?php $name = $_POST['name']; ?>
<?php $sql = "INSERT INTO xyz
(id, value) VALUES
(1, '{$name}')";
$result = $database->query($sql);
?>
i dont know why its not working but you can try like this 我不知道为什么它不起作用,但是你可以这样尝试
<form id="myForm" name="myForm" action="">
<p>
<label for="name"></label>
<input type="text" name="name" id="name" />
</p>
<p>
<input type="button" name="submit" id="submit" value="Submit" />//change type to button
</p>
</form>
also make an error callback 也使错误回调
$(function(){
$("#submit").click(function(e) {
e.preventDefault();
var name = $("#name").val();
$.ajax({
type: "POST",
url: "p.php",
data: {name:name},
success: function(){
alert("It works");
},
error:function(e){alert("it failed");}
});
});
});
您需要像这样修改表单标签:
<form id="myForm" name="myForm" action="" onsubmit="return false;">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.