1

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.

David C
  • 23
  • 5

2 Answers2

2

You should change the if clause for readyState like below:

xhttp.onreadystatechange = function () {
    if(xhttp.readyState == 4) {
        cfunc(xhttp);
    }
}

since this callback is triggered everytime the readyState changes and you are testing for the value 2 which is sent, at this point there is no response available in xhttp.responseText

See here What do the different readystates in XMLHttpRequest mean, and how can I use them?

In slightly more detail here Why XmlHttpRequest readyState = 2 on 200 HTTP response code
the difference between readyState==2 and readyState==4

Community
  • 1
  • 1
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42
0

I highly recommend using jQuery for AJAX, because it is far more simple and intuitive. Here is link for more info: http://www.w3schools.com/jquery/jquery_ref_ajax.asp

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
fico7489
  • 7,931
  • 7
  • 55
  • 89