这是我的代码。 HTML
<html>
<head></head>
</body>
<form id="myform" action="formdata.php" method="post">
username:<input type="text" name="username" id="name"><br>
password:<input type="password" name="password" id="pass"><br>
firstname:<input type="text" name="firstname" id="fname"><br>
lastname:<input type="text" name="lastname" id="lname"><br>
<input type="submit" id="submit" value="register">
</form>
<div id="status_text"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$("#submit").click(function(){
var username = $('#name').val();
var password = $('#pass').val();
var firstname = $('#fname').val();
var lastnamee = $('#lname').val();
var postData = '&username='+username+'&password='+password+'&firstname='+firstname+'&lastname='+lastname;
var status_text = $('#status_text');
//alert(postData);
//var mydata = {'username':name,'password':pass,'firstname':fname,'lastname':lname};
/*$.post($('#myform').attr('action'),
$('#myform:input').serializeArray(),
function(info){
$('status_text').html(info)
});*/
$.ajax({
url:"action",
type:"post",
success:function(info)
{
status_text.html(info);
}
});
});
</script>
</body>
</html>
这是我的数据库的PHP代码
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$conn = new mysqli($servername, $username, $password);
$name = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO karthik.person(name,password,firstname,lastname)VALUES('$name','$password','$firstname','$lastname')";
if($conn->query($sql) === TRUE){
echo("record added success");
}else{
echo("failed".$conn->error);
}
$conn->close();
?>
当我运行此代码时,它会转到下一页并显示结果,如&#34;记录已成功添加&#34;而不是我希望代码在同一页面中显示结果。我几乎尝试了所有方法,但我无法获得预期的结果。
答案 0 :(得分:1)
您需要告诉浏览器不要提交表单:
$("#submit").click(function(e) {
e.preventDefault(); // Prevents the default behaviour for the submit-action
//... the rest of your code
当你开始工作时,你应该开始修复@jeroen's list中的内容。
答案 1 :(得分:1)
你有一些问题:
$_POST
变量。