使用ajax、javascript和php发布表单数据



我试图通过JavaScript中的post AJAX调用来发布表单数据,用于我正在创建的聊天系统,以下是如何不工作的?我想找一些文档,但是找不到。

<div id="view-chat-form">
<input id="message" type="text" name="chat_message" placeholder="write a message..."/>, 
<input type="button" value="send" onclick="sendData()"/>
</div>

并使用以下AJAX代码发送请求,而不加载带有隐藏聊天id的散列字符串的页面

<script type="text/javascript">
function sendData(){
var cm = document.getElementById("message").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" + cm);
}
</script>

和以下PHP代码将消息插入到消息表

<?php
include "session.php";
include "connection.php";
$id = "";
$hashed_id = mysqli_real_escape_string($connection, $_POST["q"]);
$sql = "SELECT * FROM chats WHERE SHA2(id, 512) = ?";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 's', $hashed_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_num_rows($result);

if($count > 0){
$row = mysqli_fetch_assoc($result);
$id = $row["id"];
} else {
mysqli_free_result($result);
mysqli_close($connection);
header("Location: chat_error.php");
}

$msg = mysqli_real_escape_string($connection, $_POST["chat_message"]);
$username = $_SESSION["username"];
$date = date("d/m/Y");
$time = date("H:i:s");
$sql = "INSERT INTO chat_messages(chat_id, username, message, date, time) VALUES(?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'dssss', $id, $username, $msg, $date, $time);
mysqli_stmt_execute($stmt);
?>

不明白为什么你在javascript中使用php$_POST,它不会工作。尝试使用document.getElementById()抓取聊天消息。

正确的方法如下所示。

<script type="text/javascript">
function sendData(){
var cm = document.getElementById("message").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" + cm);
}
</script>

同样在你的PHP代码,为什么使用json_decode()?这篇文章不是JSON格式。

更改以下代码

$data = json_decode(file_get_contents("php://input"));
$hashed_id = $data->q;
$msg = $data->chat_message;

$hashed_id = $_POST["q"];
$msg = $_POST["chat_message"];

像这样做

<script type="text/javascript">
function sendData(){
var id = <?php echo $hashed_id; ?>;
var msg = <?php echo $_POST['chat_message']; ?>;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(id,msg);
}
</script>

最新更新