window.addEventListener('load',function(){
var last=0;
var sub=document.getElementById("sub");
var msg=document.getElementById('msg');
var msg_bx=document.getElementById("msg_bx");
var re=new XMLHttpRequest();
re.open("GET","handler.php?mode=begin",true);
re.onreadystatechange=function(){
if(re.status==200 && re.readyState==4){
//console.log(re.responseText);
var data=JSON.parse(re.responseText);
if(data.err_msg){
alert(data.err_msg);
}
else {
for(var o in data){
struct(data[o]);
}
}
}
}
re.send(null);
function struct(data){
s=data.sender;
m=data.msg;
t=data.time;
i=data.id;
var bx=document.createElement("div");
bx.className="msg";
msg_bx.appendChild(bx);
var sen=document.createElement("div");
bx.appendChild(sen);
sen.appendChild(document.createTextNode("Sent by:"+s));
var msg=document.createElement("div");
bx.appendChild(msg);
msg.appendChild(document.createTextNode(m));
if(i>=last){
last=i;
}
console.log(i+" "+last);
}
});
the console output displays as follows::
2 2 chat.js:64
3 3 chat.js:64
4 4 chat.js:64
5 5 chat.js:64
6 6 chat.js:64
7 7 chat.js:64
8 8 chat.js:64
9 9 chat.js:64
10 9 chat.js:64
11 9 chat.js:64
{"count1":{
"id":"2",
"sender":"1",
"msg":"bbfkjvndk?",
"time":"1386494886"
},"count2":{
"id":"3",
"sender":"1",
"msg":"bubjhadljlkvdjovjj;ojkd?",
"time":"1386494931"
},"count3":{
"id":"4",
"sender":"1",
"msg":"vidhu?",
"time":"1386494982"
},"count4":{
"id":"5",
"sender":"1",
"msg":"bvfiuefhilnfdigvfuodahfasviubjcabsyvgUVHJVKJFHV9dhf79gvhkebfvkjhdovi;h7zv9jvhdsbviy7dg89hvdsbyuavgd?",
"time":"1386495013"
},"count5":{
"id":"6",
"sender":"1",
"msg":"what the hel??",
"time":"1386495367"
},"count6":{
"id":"7",
"sender":"1",
"msg":"?",
"time":"1386497097"
},"count7":{
"id":"8",
"sender":"1",
"msg":"?",
"time":"1386497097"
},"count8":{
"id":"9",
"sender":"1",
"msg":"what do u want with me??",
"time":"1386506545"
},"count9":{
"id":"10",
"sender":"1",
"msg":"so g otbjobjsd?",
"time":"1386506554"
},"count10":{
"id":"11",
"sender":"1",
"msg":"what the hell??",
"time":"1386507581"
}} chat.php:13
The loop stops incrementing 'last' after reaching 9. The 'struct' function is utilized to create a basic structure and called whenever data is received as JSON. The 'last' variable increments with the 'i' value until it reaches 9, then remains constant even as 'i' continues to increase.