我已经包含了与我合作的代码。我试图在我的网站上异步显示评论,这些评论在带有ajax的php上运行。目前,我有一个接收用户输入的数据库(这是insert.php处理的)。我能够将用户输入输入到我的数据库中并将其打印出来,但是它不会在没有重新加载的情况下打印出index.php站点上的注释。目标是让它自动打印出用户输入,而无需重新加载站点。现在发生的事情是,一旦我按下提交按钮,它就会转到白页,一旦我再次打开index.php页面,评论就会显示出来。有些东西出错了或没有正确连接,不完全确定是什么。
的index.php
<html>
<head>
<link href="csair.css" rel="stylesheet" type="text/css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(function() {
$('#submitButton').click(function() {
$.ajax({
type: "GET",
url: "insert.php",
data: {name: $('#userInput').val()},
, beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("comment_part").html(html);
}
});
});
});
</script>
</head>
<body>
<HR SIZE="6">
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
</body>
</html>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}