Different external .js files with same variable names - javascript

I'm making a websites that displays noise measurement data from different locations. The data for each location is captured on a sound level meter device and it is then read with a windows-based application. The application then uploads data on a web server as a .js file with an array variable in it. This .js files are refreshed every 5 minutes.
I first created a javascript application that displays live data for a single measuring unit. But now I need to display data on a map for all the locations. The problem is that the windows application on each location makes a file with the same name and same variables only on another location. I'm having some trouble with reading the correct data.
This is what I did so far:
function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
function updateData(){
var numberOfNoiseSniffers = noiseSniffers.length-1;
var j = 0;
for (i=0;i<=numberOfNoiseSniffers;i++) {
file = '../'+ noiseSniffers[i] + "/" + "CurrentMeasurement.js";
$.include(file,function(){
laeq[j] = currentMeas[1][1];
lastUpdate[j] = currentMeas[0][1];
if (j==numberOfNoiseSniffers){
updateMarkers();
}
removejscssfile(file[0], "js");
j++;
});
}
t=setTimeout(function() { updateData() }, 300000);
}
$(function (){
map = new google.maps.Map(document.getElementById("gMap"), myOptions);
//noiseSniffers is an array where I have save all the folder names of different measurement locations
var numberOfNoiseSniffers = noiseSniffers.length-1;
var j = 0;
for (i=0;i<=numberOfNoiseSniffers;i++) {
var file = '../'+ noiseSniffers[i] + "/" + "CurrentMeasurement.js";
//I am using include plugin for jquery to include files because it has a callback for when a file is actually loaded
$.include(file,function(){
//a set of global arrays that keep the data from the loaded file and this data is then displayed in google maps markers
laeq[j] = currentMeas[1][1];
lastUpdate[j] = currentMeas[0][2];
latitude[j] = systemstats[12][5];
longitude[j] = systemstats[11][6];
//checking to see if I am in the process of including the last file
if (j==numberOfNoiseSniffers){
//a function that creates google maps markers
createMarkers();
}
//after that I remove the files that were just included and read
removejscssfile(file, "js");
j++;
});
}
setTimeout(function() { updateData() }, 300000);
});
I got the function for removing my .js file here: Dynamically removing an external JavaScript or CSS file.
And this is the jquery plugin for loading the .js file: Include File On Demand.
The initial load usually works (sometimes it happens that only one or no markers get loaded. But the update function mostly returns the same data for both locations.
So what I want to know is, how can I firstly make my code working and how to optimize it. I posted just the main parts of the javascript code, but I can provide all the code if it is needed. Thanks for any help.

I think you need some sort of JSONP-like solution.
Basically load data on the server side, then wrap it in a method call before returning it to client side. Your response should look something like this:
var location_data = [1,2,3,4]
updateLocation('location_id', location_data)
Now you define an updateLocation() function in your client side script. Now, every time you need new data, you create new 'script' tag with src pointing to your server side. When the response is loaded, your updateLocation() will be invoked with correct params.
I hope this is clear enough

You can maybe try some form of namespacing

i exactly dont understood your problem, but you may try this
//put your code inside an anonymous function and execute it immediately
(function(){
//your javascript codes
//create variable with same names here
//
})();

Related

Google Apps Script does not fully execute for other users after V8 was introduced

I wrote a script (with a lot of assistance from the good folks here) that copies a folder (and contents) on Google Drive using Google Sheets Scripts.
It worked fine for a long time but then I enabled the V8 engine (disabled now). The problem is, it still works for me (and maybe two other users) but does not work for everyone else. I'm not a programmer but I learned enough to help me automate some tasks on Excel/ Sheets.
So far, I've tried rechecking all the permissions, creating a brand new sheet, assigning new owners, removing triggers, learning more about V8. But it's not really working because I can't even figure out the problem.
I would appreciate any leads. TIA
PS: We're using shared drives and the Source/Target folder are accessible to all users.
Here's the script:
function onClick() {
ss.getRange("B2:B8").clearContent();
}
function start() {
var sourceFolder = ss.getRange("B19").getValue() ; // Change every month
var targetFolder = ss.getRange("B22").getValue();
var source = DriveApp.getFoldersByName(sourceFolder); // Grab the folder we're going to copy
var parentFolder=DriveApp.getFolderById(ss.getRange("B11").getValue()); // Destination for the new folder.
var target = parentFolder.createFolder(targetFolder);
if (source.hasNext()) {
copyFolder(source.next(), target);
}
}
function copyFolder(source, target) {
var folders = source.getFolders();
var files = source.getFiles();
var prefix = ss.getRange("B23").getValue();
while(files.hasNext()) {
var file = files.next();
file.makeCopy(file.getName(), target).setName(prefix + file.getName());
}
while(folders.hasNext()) {
var subFolder = folders.next();
var folderName = subFolder.getName();
var targetFolder = target.createFolder(folderName);
copyFolder(subFolder, targetFolder);
var NewFolderUrl = target.getUrl()
SpreadsheetApp.getActiveSheet().getRange('B8').setValue(NewFolderUrl);
}
//file.setName(prefix + file.getName());
}
Since you are not getting any logs for the users the script doesn't work for, the issue is most likely related to your functions not being executed properly and/or at all.
A issue for this is that the script is not being attached to the spreadsheet. You can try and declare the ss variable to the start function. Another issue for the behavior mentioned can be caused by passing wrong variables to the functions. You can check that by using console.log() and checking if the variables are the expected ones or not.
Moreover, since you share this script with multiple users, you might want to take a look into Edditor add-ons. This can make sharing easier as the users will only need to install the add-on.
Reference
Apps Script Troubleshooting;
Editor add-ons.
Through some trial and error - I've found that all someone had to do to run this script successfully was to open the SourceFolder once. It may be because it searches for it based on the file name.

Access Google App Functions in jquery/javascript

I am using google app scripts on google sites. I have created a navigation menu, and I embedded it into the page. I want to get the pageURL() from google scripts and retrieve it in my JavaScript page. I tried using the scriptlet to get the value, but it doesn't execute. Here is what I have so far. How can I get access to values in google app scripts and use them in my JavaScript function?
google script (.gs)
function getPageName(){
var site = SitesApp.getSite("site.com", "sitename");
var page = site.getChildren()[0];
var pageName = page.getUrl().split("/").splice(-1)[0];
return pageName;
}
javascript file
var pageName = <?!= getPageName()?>; // doesnt execute, need to get page url
if(pageName == linkName){
// add class here.
}
Since google loads the apps script as an iframe, I tried doing window.location.href, but it doesn't work either. The page name ends up being the name of the google app instead.
An alternative to using scriptlets is to use google.script.run (Client-side API)
It's pretty easy to use. In your case, it should be like this
code.gs
function getPageName(){
var site = SitesApp.getSite("site.com", "sitename");
var page = site.getChildren()[0];
var pageName = page.getUrl().split("/").splice(-1)[0];
return pageName;
}
Javascript File:
function onSuccess(receviedPageName)
{
if(receviedPageName== linkName)
{
// add class here.
}
}//onSuccess
google.script.run.withSuccessHandler(onSuccess).getPageName();
withSuccessHandler(function) is executed if the server-side function returns successfully or withFailureHandler(function) is executed if a server side function fails to complete the task it was assigned.
Give it a try :)

Valums file uploader: how to start with ID other than 0?

I'm using Andrew Valums' Ajax Upload plugin (GitHub link). Here is some code from it:
qq.getUniqueId = (function(){
var id = 0;
return function(){ return id++; };
})();
It's kind of a long story, but I'm in a situation where, under certain circumstances, I'd like the qq.getUniqueId function to start with an ID other than 0. It can still increment by one; it just has to start with something other than 0. What's the best way to do that?
Here are the steps to create a test environment:
Download the plugin: http://github.com/valums/file-uploader/zipball/master
Unzip it and move the "client" folder onto a web server.
Open the "demo.htm" file in a text editor, search for action: 'do-nothing.htm', and add onComplete: function(id, fileName, responseJSON) {alert(id)}, right after that.
Open the "demo.htm" file in a web browser. Be sure to access it through a web server (as opposed to just opening the local file) or else it won't work.
Upload a file. It should alert a "0" after the upload finishes. See if you can modify it so that I can pass in a different starting number.
Thanks!
Try replacing the function with one that calls the original, but adds an offset:
function offsetUniqueId(n) {
var old = qq.getUniqueId;
qq.getUniqueId = function() {
return old() + n;
}
}
See http://jsfiddle.net/alnitak/gWjqX/

Use javascript to set the image shown by Facebook sharer

I'm trying to dynamically set the thumbnail shown when sharing to Facebook using javascript. I tried adding the meta tag "og:image" to the page (it's a JSP) and that works, but what I want to do now is to replace such image with another one dynamically loaded by javascript.
Basically, the page is calling an API upon loading, using javascript, and retrieves a list of images. I want to use one of those as the thumbnail.
I tried using javascript to replace the content of the meta tag, but Facebook doesn't seem to care abou t it (it does change if I check with my browser).
Is it possible to do this?
Thanks in advance!
Here is a function I used to extract the image url from a flash object tag's flashvars parameter, and then assign it to a meta tag by using jquery:
$(window).load(function(){
//Use $(window).load() instead of $(document).ready(), so that the flash code has loaded and you have all the html you need process with javascript already in place when you start processing.
var stringToExtractFrom = $('param[name="flashvars"]').attr('value');
//Get the flashvars parameter value which we'll use to extract the preview image url from.
var pos = stringToExtractFrom.indexOf("&");
//Search for the position ampersand symbols which surround the image url.
var stringToUse;
//The final string we'll use.
var startOfImageSrc = null;
//The first position where we discover the ampersand
var endOfImageSrc;
//The second position where we discover the ampersand
var lengthToSubstract
//How many symbols to chop off the flashvars value.
while(pos > -1) {
if(startOfImageSrc == null){
startOfImageSrc = pos;
}
else {
endOfImageSrc = pos;
lengthToSubstract = endOfImageSrc - startOfImageSrc;
}
pos = stringToExtractFrom.indexOf("&", pos+1);
}
stringToUse = stringToExtractFrom.substr(startOfImageSrc+7, lengthToSubstract-7);
$('meta[property="og:image"]').attr('content', stringToUse); });
Facebook robot never runs a java script code
but why you don't try to set og tags in in server-side ?

Creating consistent URLs in jQuery

I am creating a webapp and I have been using tag in my JSPs to ensure that all my links (both to pages and to resources such as images/css) are always consistent from the root of the application, and not relative to my current location.
Some of the content I am creating using jQuery, for example, I am creating a HTML table by parsing a JSON object and using jquery.append() to insert it in to a div.
My question is, if I want to dynamically create a link using jquery how can I achieve a consistent URL regardless of the page being executed? I have tried just building the html with the tag in it, but no joy.
Thanks!
var baseURL = "/* Server-side JSP code that sets the base URL */";
$("<a />", { href: baseURL+"/my/resource/here.jsp" }); //Your proper link
Or you could do:
var baseURL = "http://"+location.host+"/my/base/url/";
//Which gives you something like http://mySite.com/my/base/url/
Get the root value of your webapp into a string using a jsp tag inside your javascript.
var root = < %=myRootVariable%> //This evaluates to http://www.myapp.com
var dynamicBit = "/foo/bar"
var dynamicLinkUrl = root + dynamicBit
var $newa = $("Hello, world");
$someJQElement.append($newa)
Hopefully none of this will occur in the global namespace. Just sayin'

Categories