不工作的XMLHttpRequest函数部分:
function save() {
//the data from the form
chat_message = document.getElementById("chat_message").value;
var from_id = document.getElementById("from_id").value;
var to_id = document.getElementById("to_id").value;
//the data string
var postdata = 'chat_message='+ chat_message + '&from_id=' + from_id +'&to_id=' + to_id;
xmlhttp.open("POST","saveChat.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postdata.length);
xmlhttp.send(postdata);
}
应该接收数据并插入数据库的saveChat.php文件:
<?php
@session_start(); //start a session for to_id
include 'dbconnect.php';
$chat = strip_tags($_POST['chat']); //messages
$from_id = $_POST['from_id'];
$to_id = $_POST['to_id'];
$timei = $_SESSION['time']; //time postes
$datei = date("Y-m-d"); //date posted
$nowId = 0; //now id
$chatId = ''; //chat id
//insert into ocmment box
$chat_user = $db_con->prepare("insert into chat_message(chat_id,message,from_id,to_id,now_id,date,time)
values(:chatId,:chat,:from_id,:to_id,:now_id,:datei,:timei)");
$chat_user->execute(array('chatId' => $chatId, 'chat' => $chat,'from_id' => $from_id, 'to_id' => $to_id, 'now_id' => $nowId,
'datei' => $datei, 'timei' => $timei));
//execute the comment
?>
假设插入消息的HTML表单:
<form name="inclusion" method="post" onSubmit="javascript: save();document.inclusion.action.focus();return false;">
<div class="input-group">
<input type="hidden" name="from_id" id="from_id" value="<?php echo $_SESSION['user']; ?>" />
<input type="hidden" name="to_id" id="to_id" value="<?php if(isset($_REQUEST['ChatId']))
echo $_REQUEST['ChatId']; else { $to_id = $db_con->prepare("select from_id from chat_message where to_id =".$_SESSION['user']); $to_id->execute(); $rowTOID = $to_id->fetch(); echo $rowTOID['from_id']; } ?>" />
<input type="text" name="chat_message" id="chat_message" placeholder="Type Message ..." class="form-control" size="50"/>
<span class="input-group-btn">
<input type="submit" value="Send" name="submit" class="btn btn-warning btn-flat"/>
</span>
</div>
</form>