Apple Web
Apple Web

Reputation: 55

console.log() only if AJAX data changed

i made this:

<script type="text/javascript">
    $('.storage').html("");
    setInterval(function(){
        $.get('./playcommand.php', function(data) {
            if($('.storage').html() !==  data){
              $('.result').html(data);
              console.log("neu");
            }
        });
    }, 500); // 5 seconds
</script>

My Intention is to console.log("neu"); only if data from AJAX is different than the data before, thats why i created a div "storage" where i save the latest data which was not equal to the data before.

But it doesnt works, it logs always "neu", even if the data isnt different.

UPDATE:

My new Code:

 <script type="text/javascript">
    var storage = $('.storage').text();
    setInterval(function(){
        $.get('./playcommand.php', function(data) {
            if($('.storage').text != data){
              $('.result').html(data);
              console.log("neu");
            }
        });
    }, 500); // 5 seconds
</script>

Still doesnt work

Upvotes: 4

Views: 108

Answers (2)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Because you are putting blank before compare. Remove this line from first line,

 $('.storage').html("");

Or keep string in one variable to compare

 var storage = $('.storage').text();
 $('.storage').html("");

And then compare data with storage

<script type="text/javascript">
     var storage = $('.storage').text().trim();;
     $('.storage').html("");
     setInterval(function(){
        $.get('./playcommand.php', function(data) {
            if(storage != data.trim()){
              $('.result').html(data);
                console.log("neu");
            }
        });
    }, 500);
</script>

Upvotes: 2

Nisal Edu
Nisal Edu

Reputation: 7591

In your code

 $('.storage').html("");

this line makes storage blank remove it or place it after the function

Upvotes: 1

Related Questions