Hi,
I'm trying to create a chat with some code I downoaded of the web and altered a bit. The updating works as long as i'm not opening up another tab page in my browser or as long as i'm not ALT+Tabbing... Which seems kinda strange to me... Also, when I submit something, the updating stops.
Since I am somewhat new to AJAX could I have some help on this issue? Don't mind the filenames though.
This is my code
[chattest.php]
<html>
<head>
<script src="selectuser.js"></script>
</head>
<body onload="setTimeout('showUser()', 500)">
<form>
Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
<input type="text" size="60" maxlength="200" name="message" id="message">
<input type="button" value="submit" name="submit" onClick="sendMsg()">
</form>
<p>
<div id="chatBox" style="overflow: scroll; height: 100px; width: 400px;"></div>
</p>
</body>
</html>
var xmlHttp;
function showUser() {
xmlHttp = createXMLHTTPObject();
if (xmlHttp == null) {
alert ("Browser does not support HTTP Request");
return;
}
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET","getuser.php",true);
xmlHttp.send(null);
}
function sendMsg() {
XML_sendMSG = createXMLHTTPObject();
if (XML_sendMSG == null) {
alert ("Browser does not support HTTP Request");
return;
}
username = "brecht";
message = document.getElementById('message').value;
//XML_sendMSG.onreadystatechange=stateChanged;
XML_sendMSG.open("GET","sendmessage.php?username="+username+"&message="+message,true);
XML_sendMSG.send(null);
}
function stateChanged() {
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById("chatBox").innerHTML=xmlHttp.responseText;
}
}
function createXMLHTTPObject() {
var object = null;
try {
// Firefox, Opera 8.0+, Safari
object = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
object = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
object = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return object;
}
[sendmessage.php]
<?php
include_once("connect.php");
if(connect() == true) {
mysql_query("INSERT INTO chat (username, message) VALUES('".$_GET['username']."', '".$_GET['message']."')") or die(mysql_error());
}
?>
[getuser.php]
<?php
include_once("connect.php");
if(connect() == true) {
$qGetMessages = mysql_query("SELECT * FROM chat ORDER BY id ASC");
while($rGetMessages = mysql_fetch_assoc($qGetMessages)) {
echo "<div>[".$rGetMessages['username']."]: ".$rGetMessages['message']."</div>";
}
}
?>
Any help would be very much appreciated.
brechtjah