我想在表zemljiste中将值'Nova parcela'添加到数据库中,所以我先写一个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;
但没有任何事情发生,这里有什么问题?
答案 0 :(得分:1)
尝试改变
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>