我试图使用此代码在mysql中的表中插入名称和密码。它会生成成功警报,但数据不会添加到表中。 有人可以解决这个问题吗?
我的html文件 -
<html>
<body>
<table border="1">
<tr>
<td align="center">Test Form</td>
</tr>
<tr>
<td>
<table>
<form onsubmit="return false" id="frm">
<tr>
<td>Name</td>
<td><input type="text" id="name" name="name" size="50">
</td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" id="password" name="password" size="50">
</td>
</tr>
<tr>
<td></td>
<td align="right">
<input type="submit" id="btnSubmit" name="submit" value="Send">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
和javascript - 我想在不加载任何其他页面的情况下进行插入(保持在同一个html页面上)。此ajax部分会弹出警报,但数据不会添加到表中。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
$("#frm").submit(function() {
var name= $("#name").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "db.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("success!");
}
});
});
</script>
最后是PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dynamic";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$order = "INSERT INTO userdata (name, password) VALUES ('$_POST[name]','$_POST[password]')";
$result = $conn->query($order);
if($result){
echo("Successfully added!");
} else{
echo("Input failed!");
}
?>
答案 0 :(得分:0)
试试这个 $ frm到#btnSubmit
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
$("#btnSubmit").click(function() {
var data = {name: $("#name").val(), password: $("#password").val()'}
$.ajax({
type: "POST",
url: "db.php",
data: data,
success: function(data) {
alert("success!");
}
});
});
</script>
答案 1 :(得分:0)
在HTML中更改代码:
<form onsubmit="return false" id="frm" method="POST">
</form>
添加表单方法POST
更改PHP代码:
$name = $_POST["name"];
$password = $_POST["password"];
$sql = "INSERT INTO userdata (name, password)
VALUES ($name, $password)";
并关闭您的连接
$conn->close();