[英]How to retrieve and insert MySQL data in a <div> tag using PHP and JQuery AJAX?
我目前正在嘗試創建一個聊天網站,該網站會接受用戶的輸入並將其顯示在輸入框上方的聊天框中,以便連接到該網站的每個人都可以看到它,但是我需要使用AJAX進行操作,以便該頁面不需要每次都刷新
我對后端Web開發非常陌生,因此,如果這是一個不好的問題,我感到非常抱歉,到目前為止,我有以下代碼,但是每次運行它似乎都不起作用:
Debate.php:
<?php
session_start();
$message = '';
$user = ($_SESSION['sessionUsername']);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$connect = new mysqli('localhost', 'root', '', 'chatBase');
$message = mysqli_escape_string($connect, $_POST['message']);
$message_query = "INSERT INTO chatlog (user, message) VALUES('$user', '$message')"; //Inserts the message and username into the database//
mysqli_query($connect, $message_query);
}
?>
<html>
<head>
<title>Debate</title>
<link rel=stylesheet href=styles.css>
<h1 class="indexTitle">Headline</h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function retrieveMessages() {
$.get("./read.php", function(data) { //executes the PHP code written in the 'read.php' file//
$chatbox.html(data); //inserts the fetched data into the div with the id 'chatbox'//
});
}
setInterval(function() {
retrieveMessages(); //executes the 'retrieveMessages' function every second//
}, 1000;
</script>
</head>
<body>
<div class="textBoxSquare" id="chatbox"></div>
<form class="form-inline" action="Debate.php" method="post">
<input class="textBoxInput" type="text" name="message" id="message">
<input class="textBoxSubmit" type="submit" value="Submit">
</form>
</body>
</html>
read.php:
<?php
$connect = new mysqli('localhost', 'root', '', 'chatBase');
$query="SELECT * FROM chatlog ORDER BY messageID ASC";
mysqli_query($connect, $query);
$res = $db->use_result();
while ($row = $res->fetch_assoc()) {
$username=$row["user"];
$text=$row["message"];
echo "<p>$user: $message</p>\n";
}
?>
用以下內容替換腳本:
function retrieveMessages() {
$.get("./read.php", function(data) {
var data = JSON.parse(data); //Parses the data from jquery to a variable.
document.getElementById("chatbox")[0].innerHTML = data; //Sets the variable to the innerHTML of that DIV ID.
});
}
setInterval(function() {
retrieveMessages();
}, 1000;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.