How to Update Firebase Value Using an HTML Button Value? - html

So I figured out how to update the value of the database, but the another problem came up. When I'm trying to update the value of a certain in the table, the output is that it updated all the values. I'm not getting the correct key when a certain button is pressed for the update. Can you guys help me with this?
My .html file
var rootRef = firebase.database().ref().child("REPORTS").child('05-21-2017');
rootRef.on("child_added", function(snapshot){
var date = snapshot.child("dateAndTime").val();
var lat = snapshot.child("latitude").val();
var long = snapshot.child("longitude").val();
var link = snapshot.child("link").val();
var report = snapshot.child("report").val();
var status = snapshot.child("status").val();
var needs = snapshot.child("needs").val();
var key = snapshot.key;
console.log(key);
var updateData = "updateData()";
$("#table_body").append("<tr id='"+snapshot.key+"'><td>"+snapshot.key+"</td><td>" +date+"</td><td>"+report+"</td><td>"+lat+"</td><td>"+long+"</td><td>"+status+"</td><td>"+needs+"</td><td><button onclick = "+updateData+">update</button></td></tr>");
});
My .js file
function updateData(key) {
var rootRef = firebase.database().ref().child("REPORTS").child('05-21-2017');
rootRef.on("child_added", function(snapshot){
var rootRef2 = firebase.database().ref().child("REPORTS").child('05-21-2017/'+snapshot.key);
console.log(rootRef2);
rootRef2.update({status: "Ongoing"});
console.log("success");
});
}
Here is what my table looks like
I want to change a particular table when i click the update button. Please help me, badly needed.

const ulTable = document.getElementById('tabla');
//Create references
const dbRefObject = firebase.database().ref().child('Users');
//Sync table changes
dbRefObject.on('child_added', snap => {
var gear = snap.child('Gear').val();
var level = snap.child('Level').val();
var strength = snap.child('Strength').val();
$(ulTable).append("<tr id="+snap.key+"><td>" + gear + "</td><td>" + level + "</td><td>" + strength + "</td></tr>");
}); //child_added
dbRefObject.on('child_changed', snap => {
var gear = snap.child('Gear').val();
var level = snap.child('Level').val();
var strength = snap.child('Strength').val();
$("#"+snap.key).html("<td>" + gear + "</td><td>" + level + "</td><td>" + strenght + "</td>");
}); //child_changed
dbRefObject.on('child_removed', snap => {
var gear = snap.child('Gear').val();
var level = snap.child('Level').val();
var strength = snap.child('Strength').val();
$("#"+snap.key).html("<td>" + gear + "</td><td>" + level + "</td><td>" + strenght + "</td>").remove();
});
My DB is:
Users -> (Gear, Level, Strength)

Related

How much faster could I make this script?

I have noticed that the script is significantly faster when I comment out the line that calls setValues(). Not that it's a super big issue, but I am interested in the different ways (if any) that I could speed the process up. If anyone has some insight, I would greatly appreciate it! It would also help me see where I could make similar optimizations in other parts of my script.
Here is the code in question:
// import new value(s)
if ((numRaw - numDk) > 0) {
var iDate;
var lastRow = getLastDataRow(earSheet, columnToLetter(earSheet.getRange("EAR_DATES_RNG").getColumn()));
var distName = impSheet.getRange("A1").getValue().toString();
var defaultDept = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("All Lists").getRange("A2").getValue().toString();
impData.forEach(function (entry) {
iDate = new Date(entry[0]);
var newEar = earSheet.getRange("A" + lastRow + ":G" + lastRow).getValues(); // init copy
if (currData.get(iDate.getTime()) == null) {
newEar[0][0] = entry[0];
newEar[0][1] = distName;
newEar[0][6] = entry[1];
newEar[0][3] = "Royalties";
newEar[0][4] = defaultDept;
newEar[0][5] = "NOT SPECIFIED";
earSheet.getRange("A" + lastRow + ":G" + lastRow).setValues(newEar);
Logger.log("ADDED: " + entry[1] + " to row: " + lastRow);
addedNewData++;
lastRow++;
}
else {
Logger.log("EXISTING DATA FOUND: " + currData.get(iDate.getTime()));
}
});
}
Using Matt and Cooper's suggestions, I came up with this revised code which is significantly faster:
if ((numRaw - numDk) > 0) {
var iDate;
var prevLastRow = getLastDataRow(earSheet, columnToLetter(earSheet.getRange("EAR_DATES_RNG").getColumn()));
var currLastRow = getLastDataRow(earSheet, columnToLetter(earSheet.getRange("EAR_DATES_RNG").getColumn()));
var rangeSize = numRaw;
var distName = impSheet.getRange("A1").getValue().toString();
var defaultDept = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("All Lists").getRange("A2").getValue().toString();
var newEar = earSheet.getRange("A" + prevLastRow + ":G" + (prevLastRow + rangeSize - 1)).getValues(); // init copy
impData.forEach(function (entry) {
iDate = new Date(entry[0]);
if (currData.get(iDate.getTime()) == null) {
newEar[currLastRow-2][0] = entry[0];
newEar[currLastRow-2][1] = distName;
newEar[currLastRow-2][6] = entry[1];
newEar[currLastRow-2][3] = "Royalties";
newEar[currLastRow-2][4] = defaultDept;
newEar[currLastRow-2][5] = "NOT SPECIFIED";
Logger.log("ADDED: " + entry[1] + " to row: " + currLastRow);
addedNewData++;
currLastRow++;
}
else {
Logger.log("EXISTING DATA FOUND: " + currData.get(iDate.getTime()));
}
});
earSheet.getRange("A" + prevLastRow + ":G" + (prevLastRow + rangeSize - 1)).setValues(newEar);
}```

Esri map with flex show name on navigator instead of coordinates

I am using com.esri.ags.components.directions on esri map and I added the stops by coordinates.
So how can I assign a name to the stop so it will be showing on screen and when printing instead of coordinates?
This is the code I added the stops into
var stop:DirectionsStop = mainUIComponent.myDirections.stopProvider[0];
stop.editable = false;
stop.searchTerm = UserSession.getCurrentUserDTO().dealerCoordinatesDTO.AddressLongitude + ","
+ UserSession.getCurrentUserDTO().dealerCoordinatesDTO.AddressLatitude;
var stopCount:int=1;
for( var i:int=0; i < customersToVisitsList.length; i++)
{
var point:DealerQuestMapPoint=new DealerQuestMapPoint(
customersToVisitsList[i].addressLongitude,customersToVisitsList[i].addressLatitude);
point.pointType="CUSTOMER";
point.targetObject=customersToVisitsList[i];
point.address = customersToVisitsList[i].address;
var imageTooltip:String//="Test";
customersToVisitsList[i].customerName.toString()
+"\n"+customersToVisitsList[i].address.toString()
+", "+customersToVisitsList[i].city.toString()
+"\n"+customersToVisitsList[i].state.toString()
+", "+customersToVisitsList[i].zip.toString();
renderMapPoint(mainUIComponent.customersLayer,
point,
customersToVisitsList[i].customer_id,
imageTooltip,
customersToVisitsList[i],
mainUIComponent.blueSymbol);
if(i==0)
{
var stop1:DirectionsStop = mainUIComponent.myDirections.stopProvider[1];
stop1.editable = true;
stop1.searchTerm = point.lon.toString() + "," + point.lat.toString();
stop1.name = customersToVisitsList[i].customerName.toString();
}
else
{
stopCount+=1;
var st:DirectionsStop = new DirectionsStop();
st.editable = true;
st.searchTerm = point.lon.toString() + "," + point.lat.toString();
st.name = customersToVisitsList[i].customerName.toString();
mainUIComponent.myDirections.stopProvider.addItem(st);
}
}
mainUIComponent.myDirections.getDirections();
I checked the documentation and I found nothing to do this because usually they deal with address but dealing with coordinates makes it a must to rename it to another name.
Screenshot of the map with coordinates written

map.fitbounds not doing anything

I have a script which takes data from html and uses it to plot routes on a map. I'm trying to get it to take all the routes and zoom to show all of them. Here's the code:
var ombounds = new google.maps.LatLngBounds(); //bounds
for (var r=1; $("#master-master > div").length; r++)
{
// Add a placemark at the start of each route
var placemark_id = "#master-" + r + " > #placemarks-data > #placemark-0";
var markerParameters = {};
markerParameters.index = r-1;
markerParameters.total = $(placemark_id + " > .total").html();
markerParameters.mapData = $(placemark_id + " > .map").html();
markerParameters.instructionsData = $("#master-" + r + " > #snippet").html();
markerParameters.distanceData = $("#master-" + r + " > #distance").html();
markerParameters.durationData = $("#master-" + r + " > #duration").html();
markerParameters.titleData = $("#master-" + r + " > #title").html();
markerParameters.urltitleData = $("#master-" + r + " > #url-title").html();
markerParameters.imageData = $(placemark_id + " > .image").html();
$.OverMap.addMarker(markerParameters);
// Draw route
var points = new Array();
var pointsData = [];
var pointsData = $('#master-' + r + ' > #route-data').html();
if (pointsData != '')
{
var pointsArray = JSON.parse(pointsData);
for (var p=0; p<pointsArray.length; p++) {
var pt = new google.maps.LatLng(pointsArray[p][0], pointsArray[p][1]);
points.push(pt);
ombounds.extend(pt); //bounds
}
$.OverMap.drawRoute(points);
}
else $.OverMap.drawDirections({preserveViewport:false});
}
(map.getBounds()); //bounds
map.fitBounds(ombounds); //bounds
For some reason, map.fitBounds(ombounds) does nothing. The code still plots the routes, but I can't see what the bounds related functions are doing. I've added //bounds to all the lines related to the zooming - at the moment, they have no visible affect on the code's output. Anyone know where I'm going wrong?
When the preserveViewport option of the directions service is set to false, each call to the DirectionsRenderer will zoom and center the map on its result. If you want fitBounds to override it, you need to set that to true.

getRange(),setFormulas doesn't want to work

I have the following code and when I run it I get the right number of items in sheetFormulas (4), and the array values look correctly formed.
However, I get an error right after the sheetFormulas Browser.msgBox pops up, indicating the getRange().setFormulas line has an issue, but I can't see what it is.
function test(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var testingTarget = ss.getSheetByName("Testing");
var sheetFormulas = new Array();
for (l=0;l<10;l++) {
sheetRowCount = l + 2;
var monthlyTotalCompanyCosts = '=F' + sheetRowCount + '/$F$29*$I$14';
var monthlyTotalCompanyCostsPerEa = '=IFERROR(H' + sheetRowCount + '/C' + sheetRowCount + ')';
var monthlyMargin = '=D' + sheetRowCount + '-F' + sheetRowCount;
var monthlyMarginPctg = '=IFERROR(J' + sheetRowCount + '/D' + sheetRowCount + ')';
sheetFormulas.push(monthlyTotalCompanyCosts,monthlyTotalCompanyCostsPerEa,monthlyMargin,monthlyMarginPctg);
Browser.msgBox("sheetFormulas.length is: " + sheetFormulas.length);
Browser.msgBox("sheetFormulas is: " + sheetFormulas);
testingTarget.getRange(sheetRowCount,8,1,4).setFormulas(sheetFormulas);
sheetFormulas = [];
}
}
Any help is appreciated,
Phil
First, sheetFormulas has to be a 2D array. So try doing
/* Notice the [] around sheetFormulas */
testingTarget.getRange(sheetRowCount,8,1,4).setFormulas([sheetFormulas]);
If you still see other problems, then put your code inside a try{}catch{} block and print out the exception in the catch block.
I also suggest that you print out the formula using Logger.log() before setting it on the spreadsheet.

Update jqGrid table with the results of Fusion Tables query in a Google Maps v3 page

I am looking to understand how to update a jqGrid table from Fusion Tables (FT) -
at the moment I can search or scroll on a Google Map, send an event listener that compiles a FT query of the spatial bounds of the viewport/map, to get a new set of results.
I want to use the new FT query string (or could use the Google code to retrieve the data - query.send(getData);) to update the jqGrid table with the new values.
Before I started using jqGrid, I tried/suceeded with the Google Visualisation API, and some of that code is below. Could anyone suggest how to move from table.draw, to loading/reloading a jqGrid table? Thanks a lot in advance.
function tilesLoaded() {
google.maps.event.clearListeners(map, 'tilesloaded');
google.maps.event.addListener(map, 'zoom_changed', getSpatialQuery);
google.maps.event.addListener(map, 'dragend', getSpatialQuery);
getSpatialQuery();
}
function getSpatialQuery() {
sw = map.getBounds().getSouthWest();
ne = map.getBounds().getNorthEast();
var spatialQuery = "ST_INTERSECTS(latitude, RECTANGLE(LATLNG(" + sw.lat() + "," + sw.lng() + "), LATLNG(" + ne.lat() + "," + ne.lng() + ")))";
changeDataTable(spatialQuery);
}
function changeDataTable(spatialQuery) {
var whereClause = "";
if(spatialQuery) {
whereClause = " WHERE " + spatialQuery;
}
var queryText = encodeURIComponent("SELECT 'latitude', 'longitude', 'name' FROM xxxxxxxx" + whereClause + " LIMIT 50");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
query.send(getData);
}
function getData(response) {
var table = new google.visualization.Table(document.getElementById('visualization'));
table.draw(response.getDataTable(), {showRowNumber: true});
}
Oh, and I used Oleg's code jqGrid returns blank cells as a basis for just seeing if I could get a simple multi-select table to pull data from my FT - that worked fine with the simple mod of
url: 'http://www.google.com/fusiontables/api/query?sql=' +
In case this helps someone, I've taken some of the code I came up with and pasted it below:
// You can get the map bounds via then pass it via a function (below is hacked from several functions
sw = map.getBounds().getSouthWest();
ne = map.getBounds().getNorthEast();
var whereClause = "ST_INTERSECTS(latitude, RECTANGLE(LATLNG(" + sw.lat() + "," + sw.lng() + "), LATLNG(" + ne.lat() + "," + ne.lng() + ")))";
//construct the URL to get the JSON
var queryUrlHead = 'http://www.google.com/fusiontables/api/query?sql=';
var queryUrlTail = '&jsonCallback=?'; //
var queryOrderBy = ' ORDER BY \'name\' ASC';
var queryMain = "SELECT * FROM " + tableid + whereClause + queryOrderBy + " LIMIT 100";
var queryurl = encodeURI(queryUrlHead + queryMain + queryUrlTail);
//use the constructed URL to update the jqGrid table - this is the part that I didn't know in my above question
$("#gridTable").setGridParam({url:queryurl});
$("#gridTable").jqGrid('setGridParam',{datatype:'jsonp'}).trigger('reloadGrid');