我正在使用AJAX将一些表单数据发送到php文件,并在其中完成了INSERT。我正在使用的代码似乎正确,但是没有插入任何内容。
这是表格:
<form id = "nameform" name ="nameform" method="POST">
<p>
<label>Title<input id = "title" type="text" name="title"></label>
</p>
<p>
<label><button id="title" type="button" onclick = "createCollection()">Create a new collection</button></label>
</p>
</form>
AJAX功能:
<?php
session_start();
if(isset($_SESSION["username"])) {
header("Location: home.php");
exit;
}
function createCollection(){
var title = document.getElementById('title').value;
var photo = "default.png";
if(title == ''){
alert("Insert title first!");
}
else {
$.ajax({
type: "POST",
url: "createCollection.php",
data: {
title:title,
photo:photo
},
success: function(){
console.log(title);
alert("Success!");
}
})};
}
createCollection.php
if(isset($_POST["title"]) && isset($_POST["photo"])) {
$conn = mysqli_connect("localhost", "root", "", "test") or die("Error:
".mysqli_connect_error());
$title=$_POST["title"];
$photo = $_POST["photo"];
$username = $_SESSION["username"];
$query = "insert into collection (title, photo, username) values
('$title','$photo','$username')";
$res = mysqli_query($conn, $query) or die("Error
".mysqli_error($conn));
if($res == true)
{
echo "Success";
}
else {
echo "fail";
}
mysqli_close($conn);
}
?>
每次我在“标题”字段中插入一个标题,然后按提交按钮时,都会从“成功函数()”中收到“成功”警报。我认为问题出在createCollection.php上,因为它似乎从未运行过。谢谢你的建议。
P.S:我已经检查了与我的问题有关的其他问题,看来我做得正确,但是,仍然没有按照其应有的方式做。