javascript loop exhibiting unpredictable behavior when making ajax requests

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.

Answer №1

The reason behind the statement "10" >= "9" being evaluated as false in Javascript is due to the fact that both values are considered as strings.

It appears that the variable data.id is a string type, causing the variables i and last to also be treated as strings during the comparison operation of i >= last.

To rectify this, you can convert the values to numbers before comparing them by using the following code snippet: i = +data.id;. After doing so, the comparison 10 >= 9 will evaluate to true.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving components from Ajax response data

While I have a good grasp of PHP, diving into AJAX and dealing with JSON is proving to be quite challenging for me. My PHP script simply delivers a straightforward JSON string like this: {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": ...

Restoring a file from archive in Amazon Web Services S3

As I work on a project, my current task involves uploading a collection of JSON files to Amazon S3 for mobile clients to access. To potentially lower the expenses related to individual file transfers, I am pondering whether it is achievable to unzip a fil ...

Update in slide height to make slider responsive

My project involves a list with text and images for each item: <div class="slider"> <ul> <li> <div class="txt"><p>First slogan</p></div> <div class="img"><img src="http://placehold.it/80 ...

What is the best way to repurpose the vuex module for multiple components?

Currently, I am tackling the pagination aspect of a project that involves handling a large amount of data. My initial instinct was to store this data within Vuex. However, I ended up implementing all the logic in the Vuex store module. Now, my goal is to f ...

Utilizing useEffect in the header component of ReactJS/Next.js: A Comprehensive Guide

In my next.js/react project, I have a component called header.js that is included on every page. Within this component, I've implemented a typewriter effect with rotation by using the following code snippet inside useEffect: export default function H ...

Issue with Firefox mobile's camera functionality

I am facing an issue with my web app for mobile devices where I am trying to display the mobile camera using Firefox mobile browser. I am using nodejs with express as a server and connecting to the server via localhost with my smartphone. Although Firefox ...

Issues with the event firing in the Polymer component for google-signin?

I recently set up a new starter-kit project using polymer-cli 1.7 and I'm attempting to incorporate Google authentication utilizing the google-signin element. Although the sign in button appears and works for signing in, the signedIn property isn&apo ...

Display a D3 Collapsible Tree visualization using information stored in a variable

I am currently working on an app that requires the display of a collapsible tree graph using D3. The data needed for this graph is not stored in a file, but rather within the database. It is retrieved through an Ajax call to a rest service and then passed ...

The icon for the weather on openweathermap is currently not displaying

Take a look at what my webpage looks like: http://prntscr.com/dg6dmm and also check out my codepen link: http://codepen.io/johnthorlby/pen/dOmaEr I am trying to extract the weather icon from the api call and display that icon (e.g. "02n") on the page base ...

"Troubleshooting why the jQuery Click Function is malfunctioning specifically in

Can someone help me troubleshoot this animate out script? It works fine on chrome, but not on Firefox and I can't seem to figure out why. Any suggestions? The script is designed to animate certain elements when a specific link is clicked. <scrip ...

Prompt user to save changes or cancel before closing modal (if closed by pressing ESC or clicking the backdrop)

When I manually close the modal, everything works fine. I just create a prompt and only call the BsModalRef.hide() method when the prompt (sweetalert) is closed. However, when the modal is closed using the ESC key or click-outside events provided by Boots ...

Transforming data from a particular csv file and embedding it into an html document

I am currently working on a feature that allows users to select a specific CSV file and display it as an HTML table on the webpage with the click of a button. The process involves: Selecting the desired file from a dropdown menu to determine the CSV fi ...

Tips for safeguarding AJAX or javascript-based web applications

Utilizing AJAX, this function retrieves information about an image in the database with the ID of 219 when a button is clicked. Any visitor to this webpage has the ability to alter the JavaScript code by inspecting the source code. By modifying the code a ...

ERROR: Unexpected issue occurred with v8::Object::SetInternalField() resulting in an internal field going out of bounds while utilizing node-cache in Node.js

I recently started working with API exports that contain a large amount of data, so I decided to utilize the node-cache in order to speed up the API response time, as it was taking more than 2 minutes to retrieve the data. Being new to this, I came across ...

Utilizing Vuejs and ElementUi to enhance slot filtering capabilities

I am facing an issue with a table where one of the columns is using slot-scope, and I am struggling to include that column data into the filters option. Code Component filter input <el-input v-model="filters[0].value" placeholder="Type t ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

The absence of HTML and CSS is preventing the inclusion of an Ajax image viewer, back button, and

Currently, I am experimenting with jQuery and JavaScript to create an ajax overlay image viewer for a PHP website. After adding this code snippet at the end of the 'gallery page', I can successfully open the viewer and navigate using the next and ...

Reasons why making an AJAX call from Angular is not possible

I am trying to implement this component: import {Component} from 'angular2/core'; import {UserServices} from '../services/UserServices'; @Component({ selector: 'users', template: '<h1>HOLA</h1>' ...

React.js mouse and touch events do not function properly when on a mobile device's screen

View React, javascript, CSS codes for this issue I encountered some problems with my codepen codes. The code is too long to paste here, so I have included a snippet below. You can view the full code and output screen by clicking on the link below: View O ...

Is it recommended to place the styles created by material-ui for child components after the styles generated for the parent component?

Utilizing material-ui, which utilizes JSS for styling a website. I have a component named Layout that applies margin to all its children (using the all children selector & > * in its style). This functionality works, but I would also like the child ...