-1

So i have a js function that connects to a live data stream, converts it to json, and writes the json to an html page that is used in another process. it is working as expected, but only the last line of the json is being written to the page. I know it has to be something silly that i'm overlooking, but below is the code to write it to the pages

        function displayFeed(feed) {
            if (feed.data !== undefined && feed.data.length > 0) {
                for (var i = 0; i < feed.data.length; i++) {
                    var row = null,
                        feedData = feed.data[i];
                        var a = JSON.stringify(feedData);
                        document.getElementById('mydiv').innerHTML = a;
                    console.log(feedData);
                }
            }
        }

now, in the console output there are many lines written and updated, but in the div, only the last. does anyone see what I need to do to get all of the feed written to the html page? this data would be updated pretty frequently.

Any help would be appreciated

KRL
  • 115
  • 1
  • 9

2 Answers2

0

Yes you are correct simple mistake, see commented code...

      function displayFeed(feed) {
            // init a at the start
            var a="";
            if (feed.data !== undefined && feed.data.length > 0) {
                for (var i = 0; i < feed.data.length; i++) {
                    var row = null,
                        feedData = feed.data[i];
                        // we need to add the new line to the old
                        var a  = a +  JSON.stringify(feedData) +"<BR>";

                }
                // when the loop is done we display the contents of our work
                document.getElementById('mydiv').innerHTML = a;

            }
        }
MartinWebb
  • 1,998
  • 1
  • 13
  • 15
  • Exactly - despite iterating through the array `feed.data[i]`, OP is overwriting the value of `a` with each iteration, and ultimately assigning the value of `a` to be the final value of `feed.data[i]` – Faisal Nov 06 '17 at 22:29
0

Here you're overwriting the previous contents of your div.

document.getElementById('mydiv').innerHTML = a;

Instead, append to it. Something like:

document.getElementById('mydiv').innerHTML += "<br>"+a;
Jonathan M
  • 17,145
  • 9
  • 58
  • 91