2

Display only new updates of JSON data, iterated with each value item in its own paragraph tag using jQuery/javascript.

If each item in the array inside the info key already is outputted in its own <p> tag; do not continue the loop but wait until there is a new item.

This is my JSON:

{
  "info": [
    "Hello world,",
    "how are you doin?",
    "Its not going to well for me unfortunately."
  ]
}

With this jQuery script:

function updatelog() {
 $.getJSON("/static/_info",
  function(data) {
   $.each(data, function(key, item) {
    var value = "";
    var i;
    for (i = 0; i < item.length; i++) {
     value += item[i];
     $("div").add('<p>' + value + '</p>').appendTo(document.body);
    }
   });
  });
}
var interval = window.setInterval(updatelog, 2000);

With this I get all the items but it doesn't stop iterating. I have searched the interwebs so much that my enter key has lost all hope for salvation. I guess this is pretty easy, but I'm a beginner and also not a javascript coder and i'm ready to pull my hair off. Thanks in advance.

randominstanceOfLivingThing
  • 16,873
  • 13
  • 49
  • 72
fivethous
  • 79
  • 2
  • 13
  • Possible duplicate of http://stackoverflow.com/questions/5738876/ajax-jquery-refreshing-all-content-but-i-want-new-content-only – voll Apr 23 '16 at 18:03

2 Answers2

1

You could take text of all p elements and push it to new array and then check if it includes values from your object

var data = JSON.parse('{"info":["Hello world,","how are you doin?","Its not going to well for me unfortunately."]}'),
  pText = [];

$('p').each(function() {
  pText.push($(this).text());
});

data.info.forEach(function(el) {
  if (!pText.includes(el)) {
    $('body').append('<p>' + el + '</p>');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello world,</p>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

You can generate a hash from every list-item and use it as id in the div elements. Everytime you retrieve the data you check if the corresponding id exists. If it exists then the item is already present in your page so you don't have to append it again.

function updatelog() {
    $.getJSON("/static/_info",
    function(data) {
        $.each(data, function(key, item) {
            var i;
            for (i = 0; i < item.length; i++) {
                var value = item[i];
                var hashCode = value.hashCode();
                if(!$("body").find("#" + hashCode).length){
                    $("div")
                    .attr("id", hashCode)
                    .add('<p>' + value + '</p>')
                    .appendTo(document.body);
                }
            }
        });
    });
}
var interval = window.setInterval(updatelog, 2000);

You can use this implementation for the hashCode function. Generate a Hash from string in Javascript/jQuery

String.prototype.hashCode = function() {
    var hash = 0, i, chr, len;
    if (this.length === 0) return hash;
    for (i = 0, len = this.length; i < len; i++) {
        chr   = this.charCodeAt(i);
        hash  = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
};
Community
  • 1
  • 1
jahnestacado
  • 593
  • 3
  • 9
  • Nice idea! Though, I got an error: `document.body.find is not a function`. I think it has something to do with it being a DOM/javascript function and not jQuery. Am I right? I tried to do it with `$.find()` and while i didn't get the error message, it did not stop the iteration. I'm going with the simpler solution @Nenad provided, it's all I need really. But thanks anyway, I'll fiddle around with this a little more. – fivethous Apr 23 '16 at 19:01
  • @fivethous Made a mistake due to fast typing. I 've corrected the selector `$("body").find` – jahnestacado Apr 23 '16 at 19:56
  • Unfortunately it still does not stop the iteration. I get the same values over and over, each in its own paragraph. – fivethous Apr 23 '16 at 20:40