I'm trying to allow users to add routes to points on a leaflet map, using sql queries to a database of points. Because I want each point to have more than one route that passes through it, I added additional columns: "route2", "routenumber2" till "route5", "routenumber5" to the original "route" and "routenumber".
The following code does work, but I figured it's repetitive to write it out five times, each time only with a different set of columns.
if (e.target && e.target.id == "submitrest") {
const enteredRoute = document.getElementById("input_Route").value; // from user form input
const enteredNumber = document.getElementById("input_routenumber").value;
const enteredNickname = document.getElementById("input_nick").value;
const enteredID = document.getElementById("input_cartodb_id").value;
cartoData.eachLayer(function (layer) {
// SQL to put layer in -- Building the SQL query
let sql =
"UPDATE stops " +
"SET area = '" + enteredRoute + "', " +
"route_number = '" + enteredNumber + "', " +
"nickname = '" + enteredNickname + "' " +
"WHERE cartodb_id = " + enteredID + ";"
console.log(sql);
if (enteredRoute && enteredNickname && enteredNumber && enteredID) {
fetch(url1, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: "q=" + encodeURI(sql)
})
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log("Data saved:", data);
})
What I am asking is if, like how document.getElementById
allows the user to input different data each time and send the data using the same code, there is a less repetitive way to make an sql query function that allows me to put the data into "route3" and "routenumber3" if "route2" and "routenumber2" are already full, and so on.
What I would like is a row in CartoDB to have five sets/columns routes and routenumbers that a user can input data to, preferably with less duplicated code.
So far I've tried using Javascript class constructors and the Factory Method. Can I get these to allow the the columns specified in the sql query to be variable? Thank you