Error encountered when sending information to web service repeatedly

After populating an array with data, the information is logged into a database using a web service when the array reaches a specific record count. However, upon calling the web service, I encountered an error related to a parameter being passed:

Error

TypeError: citizens1[i] is undefined
data:{lat:citizens1[i].lat,

Code

//populate array

citizens1.push({lat:marker[index].getPosition().lat(),lng:marker[index].getPosition().lng(),socialSecurityNumber:global_citizens[index].socialSecurityNumber});

if(citizens1.length == 500){            
    console.log('500 records saved');          
    window.clearTimeout( timerHandle);

    for(var i = 1; i = citizens1.length ; i++){

        //array has data since the console.log works
        console.log(citizens1[i].lat +',' +citizens1[i].lng+','+citizens1[i].socialSecurityNumber); 
         $.ajax({
                type:'POST',
                url:'logMovement.htm',
                data:{lat:citizens1[i].lat,
                      lng:citizens1[i].lng,
                      socialSecurityNumber:citizens1[i].socialSecurityNumber},
                dataType: 'json',
                success:function(data){

                    if (data == false){
                        console.log('error occured in logging data');
                    }

                }

            });          

     }

     citizens1 = [];
}

Answer №1

In an array, the elements are indexed from 0 to length-1, so the following line is incorrect:

for(var i = 1; i = citizens1.length ; i++){   // NB = is an assignment, == is a comparison 

It should be changed to:

for(var i = 0; i < citizens1.length ; i++){

An error occurs when i equals citizens1.length, as this goes beyond the bounds of the array.

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

How can one effectively handle elements or objects that are both event listeners and event triggers?

Yesterday, I posted a similar question but found it too complex and vague after further research, so I removed it. I have now created a new demo here, which should be self-explanatory for the most part. Below are the HTML and JavaScript sections: <sel ...

Material UI Input Field, Present Cursor Location

Is there a way to retrieve the current cursor (caret) position in a MaterialUI text field? https://material-ui.com/components/text-fields/ I am looking to make changes to the string content at a specific index, such as inserting a character X between cha ...

Getting URL parameters dynamically without reloading the page

Here's a particular issue I'm encountering: I've implemented the following function to fetch the GET Parameters from a URL. $(document).ready(function() { function getParam(variable) { var query = window.location.search.sub ...

How can you implement a bootstrap navigation bar in a vue.js project?

I have encountered a problem with using html in my vue project. Despite following the documentation, it seems that the html is not working properly. I am unsure if this issue could be related to the import of popper.js. I have checked my code and I believe ...

Unable to display menu content text using jQuery

Currently experimenting with jQuery to create a dynamic submenu. The goal is to have a sub menu appear when the main menu is clicked, and then disappear when an item in the sub menu is selected, revealing additional information within a div. Unfortunately, ...

Utilizing AngularJS to connect a dynamic result array to a table with varying layouts

I am struggling to bind a dynamic array result with a table using Angular JS in a different layout. Despite multiple attempts, I have not been successful in achieving the desired outcome. Any help or guidance would be greatly appreciated. var arr = [ ...

Increment the name field automatically and track the number of auto-increment variables being sent through serialization

I am trying to implement a functionality where users can add more inputs by pressing a button, each representing an additional 'guest'. The issue I am facing is with auto-incrementing the JavaScript so that new inputs are added with an incremente ...

The removeEventListener function is failing to properly remove the keydown event

Every time my component is rendered, I attach an event listener. mounted() { window.addEventListener("keydown", e => this.moveIndex(e)); } Interestingly, even when placed within the moveIndex method itself, the event listener persists and cannot ...

Easily upload a file by simply selecting it, no need to fill out a form or submit anything

I am working on adding a mail feature to a WordPress admin plugin. My goal is to allow users to attach a file dynamically and send it through email as an attachment. I have implemented an AJAX method for choosing the file upload, but I seem to be stuck. Ca ...

Using an Ajax request to fetch and display warning information

Exploring the world of MVC and Ajax, I am attempting to generate an Ajax query that will display one of three messages (High risk, Medium Risk, and No Risk) in a div when an integer is inputted. Here's my JSON method: public JsonResult warningsIOPL ...

The Google Maps application is experiencing an issue with rendering maps

Here is my code without the google map key. I am not receiving any errors, but the map is not showing up. What could I be missing? To test it out yourself, you will need to add your own map key which you can obtain from here. <!DOCTYPE html> <h ...

Tips for passing down props or all the properties of an object to create a dynamic component

I am facing an issue with a v-for loop in my project. The loop is supposed to iterate through objects in a list of todos fetched from the backend. These objects are then passed down to a child component, which displays each todo individually. However, I ha ...

Registration of Laravel Vue.js components

I am currently working on a Vue.js application in conjunction with Laravel. To get started, I registered Vue.js like this: import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import App from './compone ...

Infinite scroll causing Firebase ".length" function malfunction

My NextJs website is encountering errors related to Firebase infinite scroll. The issue seems to be with the .length property being undefined for some unknown reason. I am struggling to debug the code and make it work properly in Next.js. Any help would be ...

Separate the elements with a delimiter

I am in the process of inserting various links into a division by iterating through a group of other elements. The script appears to be as follows $('.js-section').children().each(function() { var initial = $(this).data('initial'); ...

The ng-switch function is not generating the desired code output

In my Ionic app, I have the following code snippet that I am currently viewing with ionic serve. However, when the initial ng-switch statement triggers... <span ng-switch="post.enclosure"> <span ng-switch-when="[]"> <p>def&l ...

Tips on Modifying JSON Objects with JavaScript

In the code I'm working with, there's a generated line that creates an animated sidebar using a div. The width of this sidebar is controlled by the 'v' parameter, currently set to 85. <div id="sidebar" class="inner-element uib_w_5 ...

Transferring the AJAX response into a JavaScript variable

New to AJAX and JS here. I am implementing an AJAX code that fetches data from a php service. I am trying to figure out how to store the returned data in a JavaScript variable, which I can then display on the UI. Below is my AJAX code snippet: <script ...

The nth-child selector fails to function properly with a customized MUI component in CSS

I've created a styled component as shown below: const FormBox = styled(Box)(({ theme }) => ({ width: "47vw", height: "25vh", backgroundColor: theme.palette.grey[100], borderRadius: theme.shape.borderRadius, marginLeft: ...

Parsing error: Unforeseen token encountered. Consider adding a supplementary loader to manage the output of these loaders

Could someone please break down this syntax message?.length === 1 and show me how to convert it into standard JavaScript? https://i.stack.imgur.com/20Ui6.png I am encountering an error when trying to use a Vue.js component that I downloaded from another ...