![](/img/trans.png)
[英]How to show an alert message when data is inserted to database using ajax?
[英]PHP records not inserted to database using Ajax
這是 AJAX 請求正文
阿賈克斯
var date = new Date().toLocaleTimeString();
var text=this.value;
var id=1;
$.ajax({
type: "GET",
url: "StoreMessages.php" ,
data: { room: id, msg:text,sendat:date }
});
PHP代碼
if(isset($_GET['room']))
{
$chatroom_name = $_GET['room'];
if(isset($_GET['msg']))
{
$text= $_GET['msg'] ;
if(isset($_GET['sendat']))
{
$local_time= $_GET['sendat']);
insertMessage( $text,$local_time, $chatroom_name);
}
}
}
function insertMessage($message_body,$local_time,$room_id)
{
echo "<script type='text/javascript'>alert('$message_body');</script>";
echo "<script type='text/javascript'>alert('$local_time');</script>";
echo "<script type='text/javascript'>alert('$room_id');</script>";
$conn = new mysqli($GLOBALS['server'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db_name']);
if($conn==false)
{
die("unable to connect database");
}
$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES ('$message_body', '$local_time', '$room_id')";
if(mysqli_query($conn,$sql)){
echo "record inserted successfully"."<br/>";
}
else{
echo "error".mysqli_error($db_conn);
}
解釋
ajax 調用在用戶輸入消息並按回車鍵時觸發 ajax 數據字段變量包含我檢查的值,然后通過設置警報,當我通過在 php 代碼中設置警報來檢查數據字段變量值時,只有文本變量包含值,並且沒有出現警報框對於其他變量,我正在嘗試將實時聊天存儲到數據庫
調試此問題的第一步是/正在診斷故障發生的位置。 去做這個:
network
選項卡network
選項卡中的請求response
選項卡**如果請求的狀態代碼是 500,這也表明腳本在 PHP 端失敗。 轉到服務器並查看錯誤日志。
從我們在response
選項卡中得到的response
我們確定問題是這一行的尾隨右括號:
$local_time= $_GET['sendat']);
此外,您應該使用參數化查詢。 任何字段中的單引號都會破壞您的查詢。
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
大致:
$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES (?, ?, ?)";
然后prepare
它, bind
值,並execute
查詢。
另外我會發回一個 JSON 對象而不是 JS 代碼。 看看http://php.net/manual/en/function.json-encode.php 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.