由於某種原因,我的聊天系統沒有發送消息&我找不到我做錯了什麼。我有我的php網頁上的聊天室,但消息不會發送。PHP/Js聊天系統
當我刪除我的數據庫密碼時,我在網頁上發現錯誤,所以我知道這是中途工作。我也知道我在表格動作上有一個#
。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Blog - Chat</title>
<link rel="stylesheet" href="http://localhost/blog/CSS3/chat.css" type="text/css">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="C:\\xampp\htdocs\blog\Chat\Javascript\chat.js"></script>
</head>
<body>
<h3> Welcome <?php print $_SESSION['user_id']; ?>! </h3>
<div class="chat">
<div class="chat-status">Status: <span>Idle</span></div>
<div class="chat-messages"></div>
<textarea class="chat-textarea" placeholder="Type your message"></textarea>
<form action="#" onSubmit ='return false;' id="chatForm">
<input type="hidden" id="username" value="<?php echo $_SESSION['user_id']; ?>"/>
<input type="submit" id="sbutton" name="submit" value="Send"/>
</div>
</body>
</html>
sendchat.php
$con = new PDO('mysql:host=127.0.0.1;dbname=chat','root','');
if(isset($_POST['text']) && isset($_POST['username']))
{
$text= strip_tags(stripslashes($_POST['text']));
$username= strip_tags(stripslashes($_POST['username']));
if(!empty($text) && !empty($username))
{
$insert = $con->prepare("INSERT INTO messages VALUES('','".$username."','".$text."')");
$insert->execute();
echo "<li class='cm'><b>".ucwords($username)."</b> - ".$text."</li>";
}
}
這是我的JS文件
$(function(){
$(document).on('submit','#chatForm',function(){
var text = $.trim($("#text").val());
var username = $.trim($("#username").val());
if(text != "" && username != ""){
$.post('sendchat.php',{text: text, username: username},function(data){
$(".chat-messages").append(data);
});
}else{
alert("Data missing");
}
});
function getMessages(){
$.get('getmessages.php',function(data){
$(".chat-messages").php(data);
});
}
setInterval(function(){
getMessages();
},500); });
getmessages.php
$con = new PDO('mysql:host=127.0.0.1;dbname=chat','root','');
$query = $con->prepare("SELECT * FROM messages");
$query->execute();
//Fetch
while($fetch = $query->fetch(PDO::FETCH_ASSOC))
{
$username = $fetch['username'];
$message = $fetch['message'];
echo "<li class='cm'><b>".ucwords($username)."</b> - ".$message."</li>";
}
什麼是錯誤?你是否啓用了error_reporting? – Matheno
爲什麼'VALUES('','?你忘記告訴你要在你的表格中插入哪些字段? –
沒有錯誤,我的消息就不會發送到聊天中 – David