php - 使用ajax插入MySql数据库

标签 php jquery mysql ajax

我想使用 ajax 将数据从表单插入到数据库中。当我运行它时,它只显示 index.php 代码并且什么都不做。我无法找出错误。所以,请帮我运行这段代码。

索引.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>

插入.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';
}
}
?>

最佳答案

如果你的表结构如下:

id int PK (Auto_increment)
name varchar(30) not null

您必须使用以下代码:

索引.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>

插入.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';
        }
    }
?>

如果您有任何困惑,请告诉我。

谢谢...

关于php - 使用ajax插入MySql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41176783/

相关文章:

javascript - 尝试向 jQuery 对象添加 HTML 类属性

php - 如何在Jquery DataTable中添加编辑和打印按钮?

php - PHP多级登录

javascript - JQuery 设置 asp 文本框的值并在回传到服务器时获取值

mysql - 使用 Angularjs 下载 csv 格式

java - 如何一次在多个表中添加行?

java - 使用 Json 实时搜索 MySQL 数据库并在 ListView android 中显示结果

javascript - JQuery UI 两个带有 from 和 to 字段的日期选择器。从所选日期起禁用 5 天

php - 插入时的 Codeigniter 根据所选的单选按钮更新其他表

javascript - Slick Slide 删除响应式断点上的内联样式