gpt4 book ai didi

javascript - 使用 ajax 和 php 向数据库添加值

转载 作者:行者123 更新时间:2023-11-29 00:17:44 25 4
gpt4 key购买 nike

我想将值“Nova parcela”添加到表 zemljiste 中的数据库,所以我先编写 ajax 代码:

<script>
var nova_parcela = 'Nova parcela';
$("#dodaj").click(function() {
$.ajax({
url: "insert.php",
type: "POST",
async: true,
data: { name:nova_parcela}, //your form data to post goes here as a json object
dataType: "html",

success: function(data) {
$('#output').html(data);
drawVisualization();
},
});

});
</script>

之后我写了 php 代码:INSERT.php 是:

    if ($_SERVER['REQUEST_METHOD'] == "POST") {

if (!$_POST['name']!='Nova parcela') {
echo "<p>Popunite sva polja</p>";
exit;
} else {
try {
$DBH = new PDO($dsn, $user, $pass, $opt);
$STH = $DBH->prepare("INSERT INTO zemljiste (naziv) VALUES (:name)");

$STH->bindParam(':name', $_POST['name']);

$STH->execute();

} catch (PDOException $e) {
echo $e->getMessage();
}
echo "<p>Data submitted successfully</p>".$_POST['ajdi'];

}

}

$DBH = null;

但是什么都没发生,这里有什么问题吗?

最佳答案

尝试改变它

   if (!$_POST['name']!='Nova parcela') {

  if (!isset($_POST['name'])) {

编辑:

if (isset($_POST['name'])) {

try {
$DBH = new PDO($dsn, $user, $pass, $opt);
$STH = $DBH->prepare("INSERT INTO zemljiste (naziv) VALUES (:name)");

$STH->bindParam(':name', $_POST['name']);

$STH->execute();
$datas['msg']= "success" ;
} catch (PDOException $e) {
echo $e->getMessage();
}

$DBH = null;
echo json_encode($datas);
}

和你的脚本:

  <script>
var nova_parcela = 'Nova parcela';
$("#dodaj").click(function() {
$.ajax({
url: "insert.php",
type: "POST",
async: true,
data: { name:nova_parcela}, //your form data to post goes here as a json object
dataType: "json",

success: function(data) {
if (data.msg == 'success'){
$('#output').html("<p>Data submitted successfully</p>"+nova_parcela);
drawVisualization();
}
else{
$('#output').html("<p>Popunite sva polja</p>");
}
}
});

});
</script>

关于javascript - 使用 ajax 和 php 向数据库添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22355309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com