Question

I've got a chat function in my website for two users to chat with each other, and I'm using JavaScript, AJAX, and PHP for it.

At the moment, it won't refresh the chat area automatically unless I submit a reply to the chat or refresh the page. I can't figure out why.

JavaScript Function

function checkReply(threadid) {
    // XMLHttpRequest
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("chatwrap").innerHTML = xmlhttp.responseText;
            setInterval(checkReply(threadid), 10000);
        }
    }
    xmlhttp.open("GET","inc/chatreply.php?chatid="+ threadid,true);
    xmlhttp.send();
}

The event handler is on the <div> the responseText will end up in:

<div id="chatwrap" onload="checkReply('.$threadid.')"></div>

$threadid is a GET variable set at the top of the page:

$threadid = (int)$_GET['chatid'];
Était-ce utile?

La solution

UPDATE

Seeing that you were in a PHP state already, the syntax was correct.

The problem is that the div doesn't possess an onload event. You'll have to attach it to the body tag, or include a script in the head or below the div, as it will only execute after the div has been rendered.


You're not including the PHP variable correctly. At the moment you are passing the string .$threadid. to the checkReply function. You will have to drop into PHP mode again before using this syntax by using the delimiters <?php & ?>.

<div id="chatwrap" onload="checkReply(<?php echo $threadid; ?>)"></div>

This should work better.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top