I'm trying to create a chatbox using AJAX but for some reason my xhttp.responseText is empty. In firebug I can see that a GET request is being sent and it even responds with the correct text, but this text just doesn't get put in the responseText for some reason.
Here is my index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chatroom</title>
<script>
function setup() {
ajaxRequest( 'GET', 'loadmessages.php', updateChat);
setInterval(function () {
ajaxRequest( 'GET', 'loadmessages.php', updateChat);
}, 1000);
}
function updateChat(xhttp) {
document.getElementById( 'chat' ).innerHTML = xhttp.responseText;
}
function ajaxRequest( method, file, cfunc ) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(xhttp.readyState == 2 && xhttp.status == 200) {
cfunc(xhttp);
}
}
xhttp.open( method, file, true);
xhttp.send();
}
</script>
</head>
<body onload="setup();">
<div id="chat">
</div>
</body>
</html>
Here is loadmessages.php:
<?php
include( 'connect.php' );
$query = "SELECT * FROM messages ORDER BY id DESC";
$result = mysqli_query($conn, $query);
if( mysqli_num_rows($result) > 0 ) {
$output = "";
while( $row = mysqli_fetch_assoc($result) ) {
$id = $row['id'];
$name = $row['name'];
$content = $row['content'];
$time = $row['time'];
$output .= "[sent by $name on $time] $content <hr/>";
}
echo $output;
} else {
echo "No messages yet, be the first to send one!";
}
mysqli_close($conn);
?>
And the connect.php:
<?php
$conn = mysqli_connect( 'localhost', 'root', '', 'chatroom' ) or die( 'Couldn\'t connect to database!' );
?>
Since there's nothing in the database yet, it just echoes "No messages yet, be the first to send one!". I can see this response if I open firebug, but this text is not in the responseText variable.