Chibuzo
Chibuzo

Reputation: 6117

Comments are shown twice when posted through AJAX, but appear only once on page reloads

I used the following codes to add comment to a post and display it without refreshing the page, but somehow, it displays the comment twice instead of once, but it only saves it once in the database. When I refresh the page, it displays each comment only once though, so i guess the problem is with the "ajax response". Here are the codes, thanks for any help.

JavaScript:

function addComment(pid) {
    var url;
    var comment = document.getElementById("comment").value;
    xml_http = getXmlHttpObject();
    if (xml_http == null) return alert("Your browser is too old to run this page!");
    url = '../auth.php?comment=' + comment + '&pid=' + pid;
    url += '&p=' + Math.random();
    xml_http.onreadystatechange = commentStatus;
    xml_http.open("GET", url, true);
    xml_http.send(null);
}

function commentStatus() {
    $("#comm").append(xml_http.responseText);
}

PHP:

include_once('include/comment.php');
addComment($_GET['pid'], filter($_GET['comment'])); 
if(empty($_SESSION['pic'])) $pic = "images/silh.gif"; 
else $pic = "/profile/image.php/{$_SESSION['uname']}.{$_SESSION['pic']}?width=45&cropratio=1:1&image=/profile/pix/{$_SESSION['uname']}.{$_SESSION['pic']}";
echo "<div id='comments'>\n"
    ."<img src='{$pic}' align='left' style='padding-right:5px' />"
    ."<span id='bluetxt'>By {$_SESSION['uname']}</span><br />\n"
    ."<span>Posted Now</span>\n"
    ."<br /><br /><p style='clear:both'>{$_GET['comment']}</p>"
    . "</div><br />\n"; 

I purposely don't read the comment from the database, I simply post it back on the page.

Upvotes: 0

Views: 212

Answers (1)

rciq
rciq

Reputation: 1309

You probably should append the comment only when xml_http state is 4. Try it like this:

function addComment(pid) {
    var url;
    var comment = document.getElementById("comment").value;
    var xml_http = getXmlHttpObject();

    if (xml_http == null)
         return alert("Your browser is too old to run this page!");

    url = '../auth.php?comment=' + comment + '&pid=' + pid;
    url += '&p=' + Math.random();

    xml_http.onreadystatechange = function() {
        if (xml_http.readyState==4) {
            appendComment(xml_http.responseText);
        }
    };

    xml_http.open("GET", url, true);
    xml_http.send(null);
}

function appendComment(commentHTML) {
    $("#comm").append(commentHTML);
}

Upvotes: 1

Related Questions