2

I have a little problem with iterating through JSON objects. I have a JSON file which I get with AJAX, I have there 15 objects. In HTML I have a DIV in which are 3 sections: header, body and date. Every 15 sec I should update this sections with data from JSON file.

HTML:

<div class="blog">
    <span id="header">
        Blog
    </span>
    <span id="body">
        20+ Best Examples of <br>
        Coming Soon Page Design
    </span>
    <span id="date">
        May 28, 2013
    </span>
</div>

JavaScript:

$(function() {
    $.ajax({
        url: "news.json",
        success: function(result) {
            var headCont = $('#header');
            var bodyCont = $('#body');
            var dateCont = $('#date');
            var res = result.news;

            $.each(res, function(index, element) {
                for (header in res) {
                    setInterval(function() {
                        headCont.html(element.header);
                    }, 15000)
                }
            });
        }
    });
});

JSON:

{
    "news": [{
          "header": "Microsoft is starting a private beta for its iPhone keyboard",
          "body": "Microsoft has its own mobile operating system, but that hasn't stopped it from opening a public beta for a new iPhone keyboard.",
          "date": "2016-04-14T08:40:23.449Z"
        }, {
          "header": "Microsoft sues U.S. government over data gag orders",
          "body": "Microsoft wants a federal court to invalidate part of a 1986 law that it alleged has been abused by the government when authorities demand customers' data.",
          "date": "2016-03-14T08:40:23.449Z"
     }]
}
3
  • Apart from not closing your $(function() { you now run once and then update the header with the same content all the time. Commented May 9, 2016 at 11:45
  • What is the issue? intervals inside loops are always something to watch out for. One interval setting all three should suffice. Commented May 9, 2016 at 11:46
  • I think you should put the ajax inside the interval function rather than putting its callback function in it. The idea should be you send ajax request every 15 sec. Commented May 9, 2016 at 11:48

2 Answers 2

3
  1. You should never run interval on AJAX
  2. In your case you only call the server once and loop over the same data

Assuming your JSON works with your loop, perhaps you meant

function updateIt() {
   var headCont = $('#header');
   var bodyCont = $('#body');
   var dateCont = $('#date');
   $.ajax({
    url: "news.json",
    success: function(result) {
      var res = result.news;
      $.each(res, function(index, element) {
        for (header in res) {
          headCont.append(element.header);
        }
      });
    });
    setTimeout(updateIt,15000); // run after success. use always or complete if needed
  }
}

If you need to update the DIV every 15 seconds with the list of stories gotten with ONE AJAX call, then you need to loop with

var news,cnt=0,tId;
function render() {
  if (cnt >= news.length) {
    clearInterval(tId); // OR set cnt to 0 and do not return to re-iterate
    return;
  }
  var item = news[cnt];
  $('#header').append(item.header);
  $('#body').append(item.body);
  $('#date').append(item.date);
  cnt++;
}
$(function() {
.
   succes: function(result) {
     news = result.news;
     render(); // run immediately 
     var tId = setInterval(render,150000); // and schedule next run
   }
.
});

result = {
  "news": [{
    "header": "Microsoft is starting a private beta for its iPhone keyboard",
    "body": "Microsoft has its own mobile operating system, but that hasn't stopped it from opening a public beta for a new iPhone keyboard.",
    "date": "2016-04-14T08:40:23.449Z"
  }, {
    "header": "Microsoft sues U.S. government over data gag orders",
    "body": "Microsoft wants a federal court to invalidate part of a 1986 law that it alleged has been abused by the government when authorities demand customers' data.",
    "date": "2016-03-14T08:40:23.449Z"
  }]
}

var news, cnt = 0, tId;

function render() {
  console.log(cnt,news[cnt]);
  if (cnt >= news.length) cnt = 0; // rerun
  var item = news[cnt];
  $('#header').html(item.header);
  $('#body').html(item.body);
  $('#date').html(item.date);
  cnt++;
}
$(function() {
  news = result.news;
  render();
  var tId = setInterval(render, 5000);
});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="header"></div>
<div id="body"></div>
<div id="date"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

@АртурПоляков Added example that loops
1

EDIT

Check this example. It itterates over an array of objects and updates the content every 2 seconds:

var result = [
  { header: 'header0', body: 'body0' },
  { header: 'header1', body: 'body1' },
  { header: 'header2', body: 'body2' },
  { header: 'header3', body: 'body3' },
  { header: 'header4', body: 'body4' },
  { header: 'header5', body: 'body5' },
  { header: 'header6', body: 'body6' },
  { header: 'header7', body: 'body7' }
]

i = 0;
var update = setInterval(function() {
  if (result[i]) {
    $('#header').html(result[i].header);
    $('#body').html(result[i].body);
    i++;  
  } else {
    clearInterval(update);
  }  
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1>Header: <span id="header"></span></h1>
<h1>Body: <span id="body"></span></h1>

3 Comments

It is never a great idea to run Ajax inside interval.
I agree, your approach is better!
Your code is also work, thanks for the answer!) - @kapantzak

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.