[英]Cant insert into table via ajax form
我有这段代码,并且测试两个值插入到mysql数据库中时,它只是不插入任何内容。 我是在混淆值,还是我的代码有错误? 使用wamp服务器。 发生以下错误;
Undefined index: name in C:\wamp\www\info.php on line 3
Undefined index: desc in C:\wamp\www\info.php on line 4
但是我尝试使用这些值,但无法弄清楚。
index.html
<html>
<head><title></title></head>
<body>
<form id="myForm" action="userInfo.php" method="post">
Name: <input type="text" name="name" /><br />
Age : <input type="text" name="age" /><br />
<button id="sub">Save</button>
</form>
<span id="result"></span>
<script src="jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="my_script.js" type="text/javascript"></script>
</body>
</html>
userinfo.php
<?php
include_once('db.php');
$name = $_POST['name'];
$age = $_POST['age'];
if(mysql_query("INSERT INTO user VALUES('$name', '$age')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
myscript部分
$("#sub").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){ $("#result").html(info);
});
});
$("#myForm").submit( function() {
return false;
});
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
更新:仍然没有修复。 得到错误:
Notice: Undefined index: name in C:\wamp\www\userInfo.php on line 4
Notice: Undefined index: age in C:\wamp\www\userInfo.php on line 5
Insertion Failed
您可以分享正在使用的JavaScript代码吗? 没有看到ajax调用就很难帮助。
我的两分钱将是使用Firebug或本机浏览器网络流量监视程序来检查发送到服务器的标头。 您需要确保在运行ajax请求时传递所有post参数。
还要确保您的ajax请求的类型为POST,并且您要填充$ .post调用的数据字段,例如:
$.post('url_here', { "name": "form_name_value here", "desc" : "desc_for_value_here" })
更新仅将serializeArray目标定位为表单元素: https : //api.jquery.com/serializeArray/
喜欢:
$("#myForm").serializeArray()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.