Justin
Justin

Reputation: 818

Ajax only display on page update not functioning?

I'm trying to make a page that displays console output in near real-time, I have tried many things but none of them seem to work, here is my latest code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 

<html> 
<head> 
<title>CP</title> 
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function update() {
    $.ajax({
        url: "read.php",
        cache: false,
        success: function(html){            
            if(html == ohtml) {
                alert(html+" ---- "+ohtml);
            } else {
                alert(html+" ---- "+ohtml);
                var ohtml = html;
                $("#consoleOP").append(html+"<br />");  
            }
        }
    });
}

</script>
</head> 
<body> 
   <div style='width: 800px; margin-left: auto; margin-right: auto;'><p>
   <input type="button" value="Refresh" onclick="update()" /></p> 
<div id="consoleOP"></div> 
</div>
</body> 
</html>

The file 'read.php' outputs the last line of the console log, Ajax requests the page and adds it to the div every time it's clicked, even though it's the same line. I would like to only display new lines and not duplicates.

When ran, the alert() outputs 'HTMLHTMLHTMLHTML ---- undefined'.

Thanks! Justin

Upvotes: 0

Views: 122

Answers (2)

epascarello
epascarello

Reputation: 207511

else {
            alert(html+" ---- "+ohtml);
            var ohtml = html;  <-- I am local and you are treating me as a global
            $("#consoleOP").append(html+"<br />");  
        }

So you need to make it work in scope

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 

<html> 
<head> 
<title>CP</title> 
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">


jQuery(function(){

    var ohtml = null;

    function update() {
        $.ajax({
            url: "read.php",
            cache: false,
            success: function(html){            
                if(html == ohtml) {
                    alert(html+" ---- "+ohtml);
                } else {
                    alert(html+" ---- "+ohtml);
                    ohtml = html;
                    $("#consoleOP").append(html+"<br />");  
                }
            }
        });
    }

    jQuery("#btnRefresh").click( update );

});

</script>
</head> 
<body> 
   <div style='width: 800px; margin-left: auto; margin-right: auto;'><p>
   <input type="button" id="btnRefresh" value="Refresh" /></p> 
<div id="consoleOP"></div> 
</div>
</body> 
</html>

Upvotes: 1

Naren Sisodiya
Naren Sisodiya

Reputation: 7288

I think you've missed to initialize the ohtml variable, and javascript assigns undefined to it so you are getting the mentioned output

Upvotes: 0

Related Questions