javascript - posting form data with ajax javascript and php
问题描述
I'm trying to post form data though a POST AJAX call in JavaScript for a chat system I'm creating, how come the following is not working? I tried to get some documentation but I cannot find it.
<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>
and using the followin AJAX code to send the request without loading the page with an hashed string to hide the chat 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>
and the followin php code to insert the message into the messages table
<?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);
?>
解决方案
做这样的事情
<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>
推荐阅读
- php - 在用户创建时存储记住令牌
- vue.js - vue i18n 问题:当我运行我的代码时,它告诉我失败了
- haskell - 在模式匹配中首先强制评估?
- c# - 如果输入无效,如何让 switch 语句循环回
- flutter - 无状态小部件中的非最终字段
- sql - 从设定的日期减去 52 周
- java - 如何在给定 char 数组的情况下反转字符串
- tensorflow - 如何使用 TFRecordWriter 编写 tf.Data.dataset.take() 的结果?
- ruby - 是否可以将 ruby 哈希从一个文件读入另一个文件,然后使用它的值?
- node.js - 将 MERN 应用程序部署到 Heroku 时出错(前端部署成功,但后端没有部署)