I have made a simple chat script using jquery and AJAX but the huge hole in it is that i can only chat with myself properly 😛
heres the javascript for my main file
<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#status").load('ajaxLoad.php');
$("#userArea").submit(function(){
var hr = new XMLHttpRequest();
var id = '<?php echo $id; ?>';
var name = '<?php echo $name; ?>';
var url = "ajaxPost.php";
var msg = document.getElementById("messages").value;
var vars = "messages="+msg+"&id="+id+"&name="+name;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
$("#status").append(return_data);
}
}
hr.send(vars);
return false;});
});
and heres my 2nd file “ajaxLoad.php”
<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT messages,id FROM chat");
while($row = mysql_fetch_array($sql))
{
echo $row["messages"];
}
?>
Now what i need is to continually refresh “ajaxLoad.php” so that users can chat in realtime without refreshing the page…any way around this?
Be careful of making too requests to the server. It’s going to be rather intensive.