我在管理頁面上有一個嵌入式表單,它在提交時不會執行任何錯誤檢查或將數據輸入數據庫,並重新加載管理頁面。提交嵌入式表單而不重新加載頁面
當通過管理頁面加載時,add_data.php和add_user.php都會發生這種情況,但是可以在自己的頁面上工作。
如何在不重新加載頁面的情況下提交表單?
管理頁面:
<?php
require('../phpinclude/init.php');
include_once('../template/head.php');
?>
<script>
$(document).ready(function(){
$(".load_content").click(function(e){
e.preventDefault();
$("#content").load($(this).attr('href'));
});
});
</script>
<nav>
<ul>
<li><a class="load_content" href="../data/index.php">Data</a></li>
<li><a class="load_content" href="../template/add_data.php">Add Data</a></li>
<li><a class="load_content" href="../template/add_user.php">Add User</a></li>
<li><a class="load_content" href="../template/list_users.php">List User</a></li>
<li><a href="../template/logout.php">Logout</a></li>
</ul>
</nav>
<div id="content">
<!-- Content gets loaded here -->
<h2>Welcome!</h2>
</div>
添加數據頁:
<?php
require('../phpinclude/init.php');
$name = $link = $name_msg = $link_msg = $submit_msg ='';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include_once("../phpinclude/db_connect.php");
if (empty($_POST["new_name"])) {
$name_msg = "Name is required";
} else if (preg_match("#[^a-z._\-0-9]#i",$_POST["new_name"])) {
$name_msg = "Only letters, numbers . _ - allowed";
} else {
$name = sanitise($_POST["new_name"]);
$checkName = $dbh->prepare("SELECT id FROM db_data WHERE name='$name' LIMIT 1");
$checkName->execute(array($name));
if ($checkName->rowcount()) {
$name_msg = 'This name is already in use';
}
}
if (empty($_POST["new_link"])) {
$link_msg = "Link is required";
} else {
$link = sanitise($_POST["new_link"]);
$checkLink = $dbh->prepare("SELECT id FROM db_data WHERE link='$link' LIMIT 1");
$checkLink->execute(array($link));
if ($checkLink->rowcount()) {
$link_msg = 'This link address is already in use';
}
}
if($name == "" || $link == "") {
echo 'The form is missing information';
} else if ($checkName->rowcount()) {
echo 'That name is already in use';
} else if ($checkLink->rowcount()) {
echo 'that link is already in use';
} else {
$sql = "INSERT INTO db_data (name, link)
VALUES (:name, :link)";
$query = $dbh->prepare($sql);
$query->bindParam(':name', $name, PDO::PARAM_STR);
$query->bindParam(':link', $link, PDO::PARAM_STR);
$query->execute();
echo 'form SUBMITTED';
exit();
}
}
?>
<h1>Add new Data</h1>
<div>
<form action="" method="POST" role="form">
<!-- NAME -->
<label for="new_name">DATA Name</label>
<input type="text" id="new_name" name="new_name" value="<?php echo $name;?>">
<span style="color:red;"><?php echo $name_msg;?></span>
<br>
<!-- LINK -->
<label for="new_link">Link</label>
<input type="text" id="new_link" name="new_link" value="<?php echo $link;?>">
<span style="color:red;"><?php echo $link_msg;?></span>
<br>
<!-- SUBMIT -->
<input type="submit" name="Submit" value="Submit">
<span style="color:red;"><?php echo $submit_msg;?></span>
</form>
</div>
add_user.php非常相似add_data.php,只有提交多個參數。
這是'