我想使用ajax将表单中的数据插入到数据库中。当我运行它时,它只显示index.php代码而什么都不做。我无法找出错误。所以,请帮我运行这段代码。
的index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<input type="text" id="name" placeholder="Enter Text">
<button id="submit" onClick="js()" type="button"> Submit</button>
<script>
function js() {
var name = document.getElementById("name").value ;
$.ajax({
type:'POST',
data: name,
url:"insert.php",
success:function(result){
alert(success);
}
});
}
</script>
</body>
</html>
insert.php
<?php
$connection = mysqli_connect('localhost', 'root', '', 'sample');
if($_POST['name']){
$name=$_POST['name'];
$q= "insert into test ('$name')";
$query = mysqli_query($connection, $q);
if($query){
echo 'inserted';
}
}
?>
答案 0 :(得分:0)
如果你的表结构如下:
id int PK (Auto_increment)
name varchar(30) not null
您必须使用以下代码:
的index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<title>Test</title>
</head>
<body>
<input type="text" id="name" placeholder="Enter Text">
<button id="submit" onClick="js()" type="button"> Submit</button>
<script>
function js()
{
if(document.getElementById("name").value!="")
{
var name = document.getElementById("name").value ;
$.post("insert.php",{name:name},function(data){
if(data)
{
alert(data);
}
else
{
alert("Cancel.");
}
});
}
else
{
alert("Enter name.");
document.getElementById("name").focus();
}
}
</script>
</body>
</html>
insert.php
<?php
$connection = mysqli_connect('localhost', 'root', '', 'test');
if($_POST['name'])
{
$name=$_POST['name'];
$q= "insert into test(name) values ('$name')";
$query = mysqli_query($connection, $q);
if($query)
{
echo 'inserted';
}
else
{
echo 'no inserted';
}
}
?>
如果您有任何疑惑,请告诉我。
...谢谢
答案 1 :(得分:0)
请尝试以下内容......这可能对您有所帮助..
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<input type="text" id="name" placeholder="Enter Text">
<button id="submit" onClick="js()" type="button"> Submit</button>
<script>
function js() {
var name = $("#name").val();
$.ajax({
type:'POST',
data: 'name='+name,
url:"insert.php",
success:function(result){
alert(success);
}
});
}
</script>
</body>
</html>
PHP脚本如下所示。
<?php
$connection = mysqli_connect('localhost', 'root', '', 'sample');
if($_POST['name']){
$name=$_POST['name'];
$q= "INSERT INTO test (name) VALUES ('$name')";
$query = mysqli_query($connection, $q);
if($query){
echo 'inserted';
}
}
?>