Leaflet JS with loop in JavaScript - javascript

I'm trying to create a loop to add multiple markers to an Leaflet map. One marker works, but when I try to do this with a loop, the markers don't work. I receive the data for the markers from a google spreadsheet.
$(document).ready(function() {
console.log("ready!");
// ID of the Google Spreadsheet
var spreadsheetID = "spreadsheetID";
// Make sure it is public or set to Anyone with link can view
var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/1/public/values?alt=json";
$.getJSON(url, function(data) {
var entry = data.feed.entry;
var amount = entry.lenght;
var i;
for (i = 0; i <= amount; i++) {
var lat = data.feed.entry[i]['gsx$lat']['$t'];
var lon = data.feed.entry[i]['gsx$lon']['$t'];
var name = data.feed.entry[i]['gsx$name']['$t'];
var to = data.feed.entry[i]['gsx$to']['$t'];
var time = data.feed.entry[i]['gsx$time']['$t'];
var tel = data.feed.entry[i]['gsx$tel']['$t'];
var marker = L.marker([lon, lat]).addTo(mymap);
marker.bindPopup('<b>Name:</b> ' + name + '<br><b>To:</b> ' + to + '<br><b>Time:</b> ' + time + '<br><b> Tel:</b> ' + tel);
}
})
});

Your code with typo and LatLng problem fixed:
$(document).ready(function() {
console.log("ready!");
// ID of the Google Spreadsheet
var spreadsheetID = "spreadsheetID";
// Make sure it is public or set to Anyone with link can view
var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/1/public/values?alt=json";
$.getJSON(url, function(data) {
var entry = data.feed.entry;
var amount = entry.length;
var i;
for (i = 0; i < amount; i++) {
var lat = data.feed.entry[i]['gsx$lat']['$t'];
var lon = data.feed.entry[i]['gsx$lon']['$t'];
var name = data.feed.entry[i]['gsx$name']['$t'];
var to = data.feed.entry[i]['gsx$to']['$t'];
var time = data.feed.entry[i]['gsx$time']['$t'];
var tel = data.feed.entry[i]['gsx$tel']['$t'];
var marker = L.marker([lat, lon]).addTo(mymap);
marker.bindPopup('<b>Name:</b> ' + name + '<br><b>To:</b> ' + to + '<br><b>Time:</b> ' + time + '<br><b> Tel:</b> ' + tel);
}
})
});

Related

Javascript jQuery function does not define variables

I am new to JavaScript and am trying to run a JavaScript/jQuery function, where Firefox gives me the following error:
Uncaught ReferenceError: latitude is not defined
getHighLow http://localhost:5000/static/weatherballoon.js:54
<anonymous> http://localhost:5000/static/weatherballoon.js:63
weatherballoon.js:54:5
The code being referenced is below.
function getHighLow(){
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + cityID + '&key=' + geocodekey, function(data){
latitude = data.results[0].geometry.location.lat;
longitude = data.results[0].geometry.location.lng;
});
$.getJSON('https://api.openweathermap.org/data/2.5/onecall?lat='+ latitude +'&lon='+ longitude +'&exclude={alerts,minutely,hourly}&appid='+ owmkey, function(data){
var tempmin = Math.round(data.daily[0].temp.min) + '°';
var tempmax = Math.round(data.daily[0].temp.min) + '°';
document.getElementById('tempmin').innerHTML = tempmin;
document.getElementById('tempmax').innerHTML = tempmax;
});
}```
$.getJSON() is asynchronous. You're trying to use the variables before they're set in the callback.
You need to perform the second getJSON in the first one's callback function.
function getHighLow() {
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + cityID + '&key=' + geocodekey, function(data) {
const latitude = data.results[0].geometry.location.lat;
const longitude = data.results[0].geometry.location.lng;
$.getJSON('https://api.openweathermap.org/data/2.5/onecall?lat=' + latitude + '&lon=' + longitude + '&exclude={alerts,minutely,hourly}&appid=' + owmkey, function(data) {
var tempmin = Math.round(data.daily[0].temp.min) + '°';
var tempmax = Math.round(data.daily[0].temp.min) + '°';
document.getElementById('tempmin').innerHTML = tempmin;
document.getElementById('tempmax').innerHTML = tempmax;
});
});
}
function getHighLow(){
var latitude=0;
var longitude=0;
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + cityID + '&key=' + geocodekey, function(data){
latitude = data.results[0].geometry.location.lat;
longitude = data.results[0].geometry.location.lng;
});
$.getJSON('https://api.openweathermap.org/data/2.5/onecall?lat='+ latitude +'&lon='+ longitude +'&exclude={alerts,minutely,hourly}&appid='+ owmkey, function(data){
var tempmin = Math.round(data.daily[0].temp.min) + '°';
var tempmax = Math.round(data.daily[0].temp.min) + '°';
document.getElementById('tempmin').innerHTML = tempmin;
document.getElementById('tempmax').innerHTML = tempmax;
});
}```

Passing Google Spreadsheet value from Google Apps script to HTML returns undefined

I am having trouble passing a value from a Google Spreadsheet to a Javascript function on the HTML.
code.gs
function getSiteCoords()
{
var emailA = Session.getActiveUser().getEmail();
var employeesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Employees") // data pertaining to employees
var numRows=1;
while(employeesheet.getRange("A"+numRows+":A"+numRows).getValue() != "") //this will count the number of rows that are filled
{
if(employeesheet.getRange("A"+numRows).getValue()===emailA)
{
let coords = employeesheet.getRange("E"+numRows).getValue();
return coords;
}
numRows = numRows+1;
}
return "";
}
index.html
function checkPosition(position) {
console.log("Latitude: " + position.coords.latitude +
" Longitude: " + position.coords.longitude);
var lat= 54.978 ;
var long=-1.5622;
var coords = google.script.run.getSiteCoords();
console.log("Site Coords " + coords);
let calc= Math.sqrt(Math.pow(position.coords.latitude - lat , 2) + Math.pow(position.coords.longitude - long , 2));
console.log("calc: "+ calc);
if(calc>0.005)
window.location.replace("https://google.com");
}
No matter what, the coords on index.html returns undefined.

Google Scripts to draft replies to emails with keyword in subject and inputting data from Google Sheets

I'm new to Google Apps Script so I'm looking for some advice. There's multiple parts and I managed to do some of it but I'm stuck on others. Any help would be much appreciated.
I'm trying to make a script that:
drafts a reply to emails that contain specific keywords (found in the body or the subject line).
I also want it to include a template with data inputted from a Google Sheets file.
It would be preferable if the draft can be updated without making a duplicate whenever the Sheet is modified.
I plan on also including a row of values (the first one) that correspond to the Subject columns in the second row the but I haven't gotten to it yet.
Some details about the Google Sheet:
Each row corresponds to a different person and email address that regularly emails me.
The first three columns are details about the person which I include in the body of my draft.
Each column after that represents a different string or keyword I expect to find in the subject of the emails sent to me.
The rows underneath contain two patterned code-words separated by a space in one cell that I want to be able to choose from. Such as:
3 letters that can contain permutations of the letters m, g, r (for ex: mmg, rgm, rgg, gmg)
and 0-3 letters with just p's (for ex: p, pp, ppp, or blank)
I want to be able to detect the different codes and assign it to a variable I can input into my draft.
What I have so far:
I'm able to draft replies for emails within my specified filter. However, I only have it set up to reply to the person's most recent message. I want to be able for sort through the filter for specific emails that contain a keyword in the subject line when it loops through the columns.
I'm able to input static strings from the Sheet into the body of my email but I'm still having trouble with the patterned codewords.
I was able to loop through more than one row in earlier version but now it's not. I'll look over it again later.
Here's my code:
function draftEmail() {
var sheet = SpreadsheetApp.getActiveSheet(); // Use data from the active sheet
var startRow = 1; // First row of data to process
var numRows = sheet.getLastRow() - 1; // Number of rows to process
var lastColumn = sheet.getLastColumn(); // Last column
var dataRange = sheet.getRange(startRow, 1, numRows, lastColumn) // Fetch the data range of the active sheet
var data = dataRange.getValues(); // Fetch values for each row in the range
// Work through each row in the spreadsheet
for (var i = 2; i < data.length; ++i) {
var row = data[i];
// Assign each row a variable
var grader = row[0]; // Col A: Grader's name
var firstName = row[1]; // Col B: Student's first name
var studentEmail = row[2]; // Col C: Student's email
var grade = row[3].split(' '); // Col D: Grade
var pgrade = grade[1];
var hgrade = grade[0];
for (var n = 1; n < data.length; ++n) {
var srow = data[n];
var subjectCol = srow[3];
var threads = GmailApp.getUserLabelByName('testLabel').getThreads();
for (i=0; i < threads.length; i++)
{
var thread = threads[i];
var messages = thread.getMessages(); // get all messages in thread i
var lastmsg = messages.length - 1; // get last message in thread i
var emailTo = WebSafe(messages[lastmsg].getTo()); // get only email id from To field of last message
var emailFrom = WebSafe(messages[lastmsg].getFrom()); // get only email id from FROM field of last message
var emailCC = WebSafe(messages[lastmsg].getCc()); // get only email id from CC field of last message
// form a new CC header for draft email
if (emailTo == "")
{
var emailCcHdr = emailCC.toString();
} else
{
if (emailCC == "")
{
var emailCcHdr = emailTo.toString();
} else
{
var emailCcHdr = emailTo.toString() + "," + emailCC.toString();
}
}
var subject = messages[lastmsg].getSubject().replace(/([\[\(] *)?(RE|FWD?) *([-:;)\]][ :;\])-]*|$)|\]+ *$/igm,"");
// the above line remove REs and FWDs etc from subject line
var emailmsg = messages[lastmsg].getBody(); // get html content of last message
var emaildate = messages[lastmsg].getDate(); // get DATE field of last message
var attachments = messages[lastmsg].getAttachments(); // get all attachments of last message
var edate = Utilities.formatDate(emaildate, "IST", "EEE, MMM d, yyyy"); // get date component from emaildate
var etime = Utilities.formatDate(emaildate, "IST", "h:mm a"); // get time component from emaildate
if (emailFrom.length == 0)
{
// if emailFrom is empty, it probably means that you may have written the last message in the thread. Hence 'you'.
var emailheader = '<html><body>' +
'On' + ' ' +
edate + ' ' +
'at' + ' ' +
etime + ',' + ' ' + 'you' + ' ' + 'wrote:' + '</body></html>';
} else
{
var emailheader = '<html><body>' +
'On' + ' ' +
edate + ' ' +
'at' + ' ' +
etime + ',' + ' ' + emailFrom + ' ' + 'wrote:' + '</body></html>';
}
var emailsig = '<html>' +
'<div>your email signature,</div>' +
'</html>'; // your email signature i.e. common for all emails.
// Build the email message
var emailBody = '<p>Hi ' + firstName + ',<p>';
emailBody += '<p>For ' + subjectCol + ', you will be graded on #1, 2, and 3: <p>';
emailBody += '<p>Participation: ' + pgrade + '</p>';
emailBody += '<p>HW grade: ' + hgrade + '</p>';
emailBody += '<p>If you have any questions, you can email me at ' + grader + '#email.com.<p>';
emailBody += '<p>- ' + grader;
var draftmsg = emailBody + '<br>' + emailsig + '<br>' + emailheader + '<br>' + emailmsg + '\n'; // message content of draft
// Create the email draft
messages[lastmsg].createDraftReply(
" ", // Body (plain text)
{
htmlBody: emailBody // Options: Body (HTML)
}
);
}
}
}
function WebSafe(fullstring)
{
var splitString = fullstring.split(",");
var finalarray = [];
for (u=0; u < splitString.length; u++)
{
var start_pos = splitString[u].indexOf("<") + 1;
var end_pos = splitString[u].indexOf(">",start_pos);
if (!(splitString[u].indexOf("<") === -1 && splitString[u].indexOf(">",start_pos) === -1)) // if < and > do exist in string
{
finalarray.push(splitString[u].substring(start_pos, end_pos));
} else if (!(splitString[u].indexOf("#") === -1))
{
finalarray.push(splitString[u]);
}
}
var index = finalarray.indexOf(grader + "#email.com"); // use your email id. if the array contains your email id, it is removed.
if (index > -1) {finalarray.splice(index, 1);}
return finalarray
}
}
I've never coded in JavaScript before or used Google Scripts so I mostly looked at similar examples.
Thank you for any feedback.
I prefer reading code that isn't too nested. So I took the liberty to re-write your code and make it easier to read.
Your main function:
function mainFunction(){
// Use data from the active sheet
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var threads = GmailApp.getUserLabelByName('<YOUR-LABEL-HERE>').getThreads();
var subject1 = data[1][3];
// Work through each row in the spreadsheet omit headers
for (var i = 2; i < data.length; ++i) {
// Get grader's data
var grader = getGrader(data[i]);
console.log(grader);
// Loop through threads
for (j=0; j < threads.length; j++){
var thread = threads[j];
// Get last message in thread
var messages = thread.getMessages();
var lastMsg = messages[messages.length - 1];
var email = new Email(grader, lastMsg, subject1);
// Create the draft reply.
var draftMessageBody = createDraftMessage(email);
lastMsg.createDraftReply(draftMessageBody);
}
}
}
Support functions:
Function getGrader:
function getGrader(array){
var row = array
var grader = {}
grader.grader = row[0];
grader.firstName = row[1];
grader.studentEmail = row[2];
var grade = row[3].split(' ');
grader.pgrade = grade[1];
grader.hgrade = grade[0];
return grader
}
Function webSafe:
function webSafe(fullstring, grader){
var splitString = fullstring.split(",");
var finalarray = [];
for (u=0; u < splitString.length; u++){
var start_pos = splitString[u].indexOf("<") + 1;
var end_pos = splitString[u].indexOf(">",start_pos);
// if < and > do exist in string
if (!(splitString[u].indexOf("<") === -1 && splitString[u].indexOf(">",start_pos) === -1)){
finalarray.push(splitString[u].substring(start_pos, end_pos));
} else if (!(splitString[u].indexOf("#") === -1)){
finalarray.push(splitString[u]);
}
}
// use your email id. if the array contains your email id, it is removed.
var index = finalarray.indexOf(grader.grader + "#mangoroot.com");
if (index > -1) {
finalarray.splice(index, 1);
}
return finalarray
}
Function Email: Behaves like a class
var Email = function(grader, lastMsg, subject){
this.signature = "your_email_signature,";
this.grader = grader;
this.to = webSafe(lastMsg.getTo(), this.grader);
this.from = webSafe(lastMsg.getFrom(), this.grader);
this.cc = webSafe(lastMsg.getCc(), this.grader);
this.subject = lastMsg.getSubject().replace(/([\[\(] *)?(RE|FWD?) *([-:;)\]][ :;\])-]*|$)|\]+ *$/igm,"");
this.message = lastMsg.getBody();
this.date = lastMsg.getDate();
this.attachments = lastMsg.getAttachments();
this.subject1 = subject;
this.ccHeader = function() {
var ccHeader = "";
if (this.to == "" || this.cc == ""){
ccHeader = this.cc.toString();
}
else {
ccHeader = this.to.toString() + "," + this.cc.toString();
}
return ccHeader
}
this.eDate = function() {
return Utilities.formatDate(this.date, "IST", "EEE, MMM d, yyyy");
}
this.eTime = function() {
return Utilities.formatDate(this.date, "IST", "h:mm a");
}
this.header = function() {
var header = ''.concat('On ');
if (this.from.length == 0){
header += this.eDate().concat(' at ',this.eTime(),', you wrote: ');
}
else {
header += this.eDate().concat(' at ',this.eTime(),', ',this.from,' wrote: ');
}
return header
}
this.body = function(){
var grader = this.grader;
var body = '<div>'.concat('<p>Hi ',grader.firstName,',</p>');
body += '<p>For '.concat(this.subject1,', you will be graded on #1, 2, and 3: </p>');
body += '<p>Participation: '.concat(grader.pgrade,'</p>');
body += '<p>HW grade: '.concat(grader.hgrade,'</p>');
body += '<p>If you have any questions, you can email me at '.concat(grader.grader,'#mangoroot.com.</p>');
body += '<p>- '.concat(grader.grader,'</p>','</div>');
return body;
}
}
Function createDraftMessage:
function createDraftMessage(email){
var draft = '<html><body>'.concat(email.body);
draft += '<br>'.concat(email.signature);
draft += '<br>'.concat(email.header);
draft += '<br>'.concat(email.message);
draft += '<br>'.concat('</body></html>');
return draft;
}
Now when you run mainFunction() you should get your expected drafts.
Notes:
It is good practice to keep functions flat, flat is better than nested. Makes the code more readable and maintainable.
Also be consistent in your variable naming style.
var emailMsg = ''; // Good.
var emailmsg = ''; // Hard to read.
Have a read about classes

Inserting an element in a specific id based on a data attribute

I am trying to dynamically insert elements within a loop, in to the corresponding DIVs based on the dataset values. Basically if the two elements have matching dataset value, it should be inserted in to a specific div.
The dataset values are unique, however in some cases the dataset values can appear more than once.
I have used the following code in another part of the project I'm working on, however I can't seem to make it work with the next thing I need to do.
var callingPointsWrapper = document.querySelectorAll(".callingstations");
var currentCallingWrapper = [...callingPointsWrapper].find((wrapper) => wrapper.dataset.callingpointsid === trainUID);
var callingWrapperFragment = document.createRange().createContextualFragment(callingPointsTemplate);
// add to correct element
callingPointsWrapper.appendChild(callingPointsTemplate);
All my code is shown below in context. Thanks in advance.
// scripts
// change protocol to https if http
if (window.location.protocol != 'https:') window.location.protocol = 'https';
//
var info = document.querySelector(".info");
// check if geolocation works/is supported using if statement
// if geolocation is supported
if ("geolocation" in navigator) {
// log to console
console.log("GeoLocation is working.");
// function to run if geolocation is supported
navigator.geolocation.getCurrentPosition(function(position) {
// store users coords
var lat = position.coords.latitude;
var lon = position.coords.longitude;
// log them to console
console.log("Your coordinates are: " + lat + "," + lon);
// callback function to use users coordinates in another function
findNearestStation(lat, lon);
});
// if geolocation is not supported
} else {
// log to console
console.log("GeoLocation is not supported.");
}
// empty array for timetable information
var serviceUrlArray = [];
function findNearestStation(lat, lon) {
// log to console
// console.log("Your coordinates are: " + lat + "," + lon);
// api keys and tokens
var appID = "xxx";
var appKey = "xxxxxx";
// api for nearest stations url template
var transportApiUrl = "https://transportapi.com/v3/uk/train/stations/near.json?app_id=" + appID + "&app_key=" + appKey + "&lat=" + lat + "&lon=" + lon + "&rpp=5";
// ajax request to get nearest stations
var nearbyStationsReq = new XMLHttpRequest();
nearbyStationsReq.open('GET', transportApiUrl, true);
nearbyStationsReq.onload = function() {
// results window
var resultsWindow = document.querySelector(".results-window");
// empty array for the timetable urls
var timetableUrlArray = [];
// empty array for station codes
var stationCodeArray = [];
// clear the results window
resultsWindow.innerHTML = "";
if (this.status >= 200 && this.status < 400) {
// response data
var res = JSON.parse(this.response);
// variable for stations array in response
var data = res.stations;
// for loop to iterate through response data
for (var i = 0; i < data.length; i++) {
// get information from response data
var code = data[i].station_code;
var name = data[i].name;
var distanceMetres = data[i].distance;
var distanceKilometres = (distanceMetres / 1000).toFixed(1);
var distanceKilometres = distanceKilometres + "km";
// log data to console to reference
// console.log("Code: " + code + " | Name: " + name + " | Distance: " + distanceKilometres);
// generate urls for timetable data
var timetableUrl = "https://transportapi.com/v3/uk/train/station/" + code + "/live.json?app_id=" + appID + "&app_key=" + appKey + "&darwin=true&train_status=passenger";
// push completed urls to the array
timetableUrlArray.push(timetableUrl);
// push codes to empty array
stationCodeArray.push(code);
// template for nearest stations result container
var resultTemplate =
"<div class='result'>" +
"<div class='station-name'>" +
"<span class='service-origin'>" +
"<span class='nr-logo'>" +
"<img src='assets/images/nr.svg' alt='National Rail Logo'></span>" + name + "</span>" +
"</div>" +
"<div class='service-results-wrapper' data-stationcode='" + code + "'></div>" +
"</div>";
// insert template in to the results window
resultsWindow.innerHTML += resultTemplate;
}
// log to console
// console.log(stationCodeArray)
// for loop to create a request for each station
for (var i = 0; i < timetableUrlArray.length; i++) {
// ajax request for timetable request
var timetableReq = new XMLHttpRequest();
timetableReq.open('GET', timetableUrlArray[i], true);
timetableReq.onload = function() {
if (this.status >= 200 && this.status < 400) {
// response from request
var res = JSON.parse(this.response);
// data for timetable info
var data = res.departures.all;
// declare service results wrapper
var serviceResultsWrapper = document.querySelectorAll(".service-results-wrapper");
// loop to go through the data
for (var i = 0; i < data.length; i++) {
// information required
var currentStation = res.station_name;
var currentStationCode = res.station_code;
var aimedDepartTime = data[i].aimed_departure_time;
var expectedDepartTime = data[i].expected_departure_time;
var destination = data[i].destination_name;
var platform = data[i].platform;
var operator = data[i].operator_name;
var status = data[i].status;
var trainUID = data[i].train_uid;
// generate url
var serviceURL = "https://transportapi.com/v3/uk/train/service/train_uid:" + trainUID + "///timetable.json?app_id=" + appID + "&app_key=" + appKey + "&darwin=true&live=true"
// log data to console
console.log("Current Station: " + currentStation + " | Current Station Code: " + currentStationCode + " | Aimed: " + aimedDepartTime + " | Expected: " + expectedDepartTime + " | Destination: " + destination + " | Platform: " + platform + " | Status: " + status + " | Operator: " + operator + " | ID: " + trainUID + " | URL: " + serviceURL);
// if platform is null
if (platform === null) {
// change variable to string
var platform = "n/a";
}
// switch statement to change styling based on status
switch (status) {
case "EARLY":
var status = '<span class="status ontime">On time</span>';
break;
case "ON TIME":
var status = '<span class="status ontime">On time</span>';
break;
case "LATE":
var status = '<span class="status delayed">Delayed' + " " + expectedDepartTime + '</span>';
var aimedDepartTime = '<span class="time unavailable strikethrough">' + aimedDepartTime + '</span>';
break;
case "CANCELLED":
var status = '<span class="status cancelled">Cancelled</span>';
break;
case "NO REPORT":
var status = '<span class="status unavailable">Unavailable</span>';
break;
case "STARTS HERE":
var status = '<span class="status ontime">On time</span>';
break;
case "OFF ROUTE":
var status = '<span class="status unavailable">Unavailable</span>';
break;
case "CHANGE OF ORIGIN":
var status = '<span class="status unavailable">Unavailable</span>';
break;
default:
var status = '<span class="status unavailable">Unavailable</span>';
}
// template for service boxes
var serviceBoxTemplate = "<span class='service-box' data-station='" + currentStationCode + "' data-uid='" + trainUID + "'><span class='service-time-status'><span class='service-depart-time'>" + aimedDepartTime + "</span>" +
status +
"<span class='service-depart-platform'>Plat. <span class='service-platform-number'>" + platform + "</span></span></span>" +
"<span class='service-destination'><span class='service-destination-name'>" + destination + "</span></span>" +
"<span class='callingstations' data-callingpointsid='" + trainUID + "'>Leigh-on-Sea, Chalkwell, Westcliff, Southend Central, Southend East, Thorpe Bay, Shoeburyness</span>" +
"<span class='service-operator'>Operated by <span class='service-operator-by'>" + operator + "</span></div>";
// inserts correct service in to correct station element based on matching codes
var currentWrapper = [...serviceResultsWrapper].find((wrapper) => wrapper.dataset.stationcode === currentStationCode);
var serviceBoxFragment = document.createRange().createContextualFragment(serviceBoxTemplate);
// add to correct element
currentWrapper.appendChild(serviceBoxFragment);
// ajax request to get service info
var serviceReq = new XMLHttpRequest();
serviceReq.open('GET', serviceURL, true);
serviceReq.onload = function() {
if (this.status >= 200 && this.status < 400) {
// response text
var res = JSON.parse(this.response);
// get array within response text
var data = res.stops;
// get the trains UID
var trainUID = res.train_uid;
// var currentStation = res.station_name;
// new array for calling points
var callingPointsArray = [];
for (var i = 0; i < data.length; i++) {
// get the calling points station names
var callingPoint = data[i].station_name;
// push names in to an array
callingPointsArray.push(callingPoint);
// create a string and add a comma between each name
var callingPointStr = callingPointsArray.join(", ");
// split the array where the calling
var subsequentCallingPoints = callingPointStr.split(currentStation);
var callingPointsTemplate = "<span>" + subsequentCallingPoints + "</span>";
subsequentCallingPoints[1].substring(1).trim()
}
var callingPointsWrapper = document.querySelectorAll(".callingstations");
var currentCallingWrapper = [...callingPointsWrapper].find((wrapper) => wrapper.dataset.callingpointsid === trainUID);
var callingWrapperFragment = document.createRange().createContextualFragment(callingPointsTemplate);
// add to correct element
callingPointsWrapper.appendChild(callingPointsTemplate);
// // add to correct element
// currentWrapper.appendChild(callingPointsFragment);
// callingPointsWrapper[0].innerHTML = "";
// callingPointsWrapper[0].innerHTML = subsequentCallingPoints[1].substring(1).trim();
// console.log(callingPointsArray)
} else {
// We reached our target server, but it returned an error
}
};
serviceReq.onerror = function() {
// There was a connection error of some sort
};
serviceReq.send();
}
// console.log(serviceUrlArray)
} else {
// We reached our target server, but it returned an error
}
};
timetableReq.onerror = function() {
// There was a connection error of some sort
};
timetableReq.send();
}
} else {
// log to console
console.log("There is an error.");
}
};
nearbyStationsReq.onerror = function() {
// log to console
console.log("There is an error.");
};
nearbyStationsReq.send();
}
// var request = new XMLHttpRequest();
// request.open('GET', '/my/url', true);
// request.onload = function() {
// if (this.status >= 200 && this.status < 400) {
// // Success!
// var data = JSON.parse(this.response);
// } else {
// // We reached our target server, but it returned an error
// }
// };
// request.onerror = function() {
// // There was a connection error of some sort
// };
// request.send();
// x

jQuery: Adding objects to arrays in each loops not working

I'm looping through DOM elements when a certain button is clicked. I've attached the class finish-proc to the button, so when clicked will activate this function:
<script>
$(document).on('click', '.finish-proc', function () {
var communities = [];
var $this, $thisDay, input, inputDay, text, textDay, obj, objDay;
$('.panel-default').each(function (i) {
var maxPeople = '.' + $(this).attr('data-community') + '-max-people';
var dayInfoRow = '.' + $(this).attr('data-community') + '-day-info';
obj = {};
obj["maxPeople"] = $(maxPeople).val();
var daysArrayInLoop = [];
$(dayInfoRow).each(function (j) {
var objDay = {};
var dayString = '.' + $(this).attr('data-community') + '-day-' + (j + 1);
var dayStringStart = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-start';
var dayStringEnd = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-end';
objDay["dayString"] = $(dayString).val();
objDay["dayStringStart"] = $(dayStringStart).val();
objDay["dayStringEnd"] = $(dayStringEnd).val();
daysArrayInLoop.push(objDay);
}
obj["dayArray"] = daysArrayInLoop;
communities.push(obj);
}
}
</script>
This code is breaking on the line:
daysArrayInLoop.push(objDay);
With the error:
daysArrayInLoop.push is not a function
Can anyone tell me why this is?
EDIT - I've tried to alter the var daysArrayInLoop = []; to var daysArrayInLoop = {};, still getting the same error
Try This code define array after push in object
var daysArrayInLoop = new Array();
daysArrayInLoop.push(obj);

Categories