我在将表单插入数据库时遇到问题。我无法弄清楚我错在哪里......
我的表格如下:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="script.js"></script>
<form id="form" name="form">
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="submit" onclick="myFunction()" type="button" value="Submit">
</div>
</form>
脚本script.js
function myFunction() {
var name = document.getElementById("name").value;
var dataString = 'name1=' + name;
if (name == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: "ajaxjs.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
和php脚本ajaxjs.php
<?php
include ('./includes/connection.php');
$name1 = $_POST['name1'];
if (isset($_POST['name1'])) {
$query = mysql_query("INSERT INTO db VALUES('TEST','name1')");
}
?>
开发人员工具显示消息: script.js:5未捕获的ReferenceError:未定义dataStringmyFunction @ script.js:5onclick @ test.html:9
答案 0 :(得分:2)
您的Ajax代码运行良好 但是你的查询命令看起来错了 请尝试
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
更新:源代码运作良好
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function myFunction() {
var name = document.getElementById("name").value;
var dataString = 'name1=' + name;
if (name == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: "ajaxjs.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
</script>
<form id="form" name="form">
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="submit" onclick="myFunction()" type="button" value="Submit">
</div>
</form>
和ajaxjs.php
<?php
// include ('./includes/connection.php');
$name1 = $_POST['name1'];
echo $name1;
// if (isset($_POST['name1'])) {
// $query = mysql_query("INSERT INTO db VALUES('TEST','name1')");
// }
?>