Getting data into an array from a separate javascript file - javascript

So I have a huge javascript file that is named locationsarray.js. I want to however call this file into this code
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
//Do something
}
I'm not sure how to get that file into this array. Lastly I need to find a way to output the data within the file into html with new google.maps.LatLng() so that it would plot the points on the map. I'm sorry if this is vague but that's as far as my understanding goes. Please help!
The code for the outside javascript file is structured so:
var lsz = 10090;
var CountryTerritory = Array([lsz]);
var Region = Array([lsz]);
var City = Array([lsz]);
var Clicks = Array([lsz]);
CountryTerritory[0] = "United States";
Region[0] = "Florida";
City[0] = "Lauderdale-by-the-Sea";
Clicks[0] = "1";
CountryTerritory[1] = "United States";
Region[1] = "Florida";
City[1] = "Lake Lorraine";
Clicks[1] = "1";
CountryTerritory[2] = "United States";
Region[2] = "Florida";
City[2] = "Palmetto Estates";
Clicks[2] = "1";

In you HTML, include both scripts one after the other, starting with the outer:
<html>
<head>
<script type="text/javascript" src="./outerScript"></script>
<script type="text/javascript" src="./innerScript"></script>
...
</head>
<body>
...
This will make them use the same scope, so if the first script has var arr = []
You can use arr in the second.

Related

How to update Bokeh source with CustomJS

I am having some troubles while trying to update my Bokeh source when using a Select widget and CustomJS. CustomJS is a mandatory requirement in this case, so no def: function can be used.
The below code returns the data visualisation but it does not refresh as, I guess, the JS code is not properly written and I got no way to debug it (if someone knows how, please its indeed the best answer I could get).
The main idea is to filter my source based on the value selected on the Select widget.
Any ideas??
source = ColumnDataSource(data=dict(
x=gx,
y=gy,
recty=recty,
colors=colors,
filter_info= filter_info))
select = Select(title="Option:", value="All", options=["All", "1", "2", "3", "4", "5", "6+"])
renderer_source = source
# Add the slider
code = """
var value_filter_info = cb_obj.value;
if value_assignments == 'All' {
new_source_data['x'] = source.data['x'];
new_source_data['y'] = source.data['y'];
new_source_data['recty'] = source.data['recty'];
new_source_data['colors'] = source.data['colors'];
} else {
new_source_data['x'] = source.data['x'][source.data['filter_info']==value_filter_info];
new_source_data['y'] = source.data['y'][source.data['filter_info']==value_filter_info];
new_source_data['recty'] = source.data['recty'][source.data['filter_info']==value_filter_info];
new_source_data['colors'] = source.data['colors'][source.data['filter_info']==value_filter_info];
}
renderer_source.data= new_source_data;
renderer_source.change.emit();
"""
callback = CustomJS(args=dict(source=source, renderer_source=renderer_source), code=code)
select.js_on_change('value', callback)
p = figure(plot_width=1200, plot_height=400, x_range=(0,100), y_range=(0,1000))
p.rect(x='x', y='recty', width=1, height=1, color='colors', source=renderer_source, line_color=None, fill_alpha=1, width_units="data", height_units="data")
plot_layout = column(select,p)
show(plot_layout)
output_notebook()
Many thanks!
So I found a solution that can be aesthetically, programatically, and visually improved but at least the outcome is shown.
Following the advice by #bigreddot on indexing and overwriting, I managed to write the current CustomJS code:
code = """
var render=renderer_source.data;
var data=source.data;
var data_assignment = data['assignments'];
var value_assignments = cb_obj.value;
var data_x=data['x'];
var data_y=data['y'];
var data_recty=data['recty'];
var data_colors=data['colors'];
var render_x=render['x'];
var render_y=render['y'];
var render_recty=render['recty'];
var render_colors=render['colors'];
var x = [];
var y = [];
var recty = [];
var colors = [];
render_x=[];
render_y=[];
render_recty=[];
render_colors=[];
for (var i=0;i<data_assignment.length; i++){
if (value_assignments == 'All') {
x.push(data_x[i]);
y.push(data_y[i]);
recty.push(data_recty[i]);
colors.push(data_colors[i]);
} else if (data_assignment[i]==value_assignments) {
x.push(data_x[i]);
y.push(data_y[i]);
recty.push(data_recty[i]);
colors.push(data_colors[i]);
}
}
renderer_source.data['x']=x;
renderer_source.data['y']=y;
renderer_source.data['recty']=recty;
renderer_source.data['colors']=colors;
renderer_source.change.emit();
"""

Push/update array from JavaScript to HTML

I have made a array of data from Firebase, and want to display it on my website. It works fine one time, but when Firebase is updated, the website doesn´t update correspondingly.
My goal is to make a list of updates. So when the database is updated, the new update is shown above the previous.
console.log(arr); logs every change made in the database, so basically I want what the console displays..
JS code:
firebase.initializeApp(config);
database = firebase.database();
var ref = database.ref("users");
ref.on("value", gotData, errData);
function gotData(data) {
// console.log(data.val);
var users = data.val();
var keys = Object.keys(users);
//console.log(keys);
for (var i = 0; i < keys.length; i++) {
var k = keys [i];
var name = users [k].Name;
var gender = users [k].Gender;
var car = users [k].Car;
var location = users [k].Location;
var destination = users [k].Destination;
// initialize array
var arr = [
name,
gender,
car,
location,
destination,
];
// append new value to the array
arr.push(destination);
document.getElementById('B1').innerHTML = JSON.stringify(arr);
console.log(arr);
}
}
function errData(err) {
console.log("Error");
console.log(err);
}
<!DOCTYPE html
<html>
<head
<meta charset="utf-8">
<title>Test</title>
<script src="https://www.gstatic.com/firebasejs/live/3.1/firebase.js"></script>
</head>
<body>
Test
<!-- Value -->
<ol id="B1"></ol>
<script src ="App.js"></script>
</body>
</html>
Firebasestructure:
App
users
09IEbFijEnQpDita5DyhUdBE0eD3
Name: "Nick"
Car: "Audi"
Gender: " Male"
Location: "Home"
Destination: " Beach"
Is there a good (and hopefully not to complicated) way to reach my goal?
Thank you.
You are resetting your array in every iteration, while you really want to keep the data from the previous iterations in there. So intitialise your array before entering the loop, and only add to it within the loop. In the same way you overwrite the output in the HTML element in each iteration. Instead, accumulate the data in the loop and only output the array after the loop:
function gotData(data) {
var users = data.val();
var keys = Object.keys(users);
// initialize array here
var arr = [];
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var name = users[k].Name;
var gender = users[k].Gender;
var car = users[k].Car;
var location = users[k].Location;
var destination = users[k].Destination;
// append new value to the array
arr.push([
name,
gender,
car,
location,
destination,
]);
}
// And now output:
document.getElementById('B1').innerHTML = JSON.stringify(arr);
console.log(arr);
}
All this can be done a bit shorter with the use of Object.values (assuming you want all the data fields):
function gotData(data) {
var arr = Object.values(data.val()).map(Object.values);
document.getElementById('B1').innerHTML = JSON.stringify(arr);
console.log(arr);
}
If you want the last value at the top of the output then use the reverse method, and if you want it in a list format then map the values to li tags. Finally, you may want to limit the number of rows to some constant (e.g. 10), which you can do with slice:
function gotData(data) {
var arr = Object.values(data.val()).map(Object.values);
B1.innerHTML = arr.slice(-10).reverse().map(val => `<li>${val}</li>`).join('');
}
Note that you don't really need document.getElementById nowadays, since browsers declare global variables for each of the elements with an id attribute. So you can just use the B1 variable.

How can i use script parameters into my js file?

I have this script code:
<script src="http://example.com/embed.js?q=123&parameter1=450&parameter2=300"></script>
How can i get the values of q(123)and parameter1(450) and parameter2(300) and use them into embed.js file? I want to make conditions into my embed.js by using these values. How can i achieve that?
Give the script element and ID attribute like this:
<script id="embed-script" src="http://example.com/embed.js?q=123&parameter1=450&parameter2=300"></script>
Javascript:
var url = document.getElementById('embed-script');
function parseGet(val) {
var result = "",
tmp = [];
var items = url.src.split("?")[1].split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val)
result = decodeURIComponent(tmp[1]);
}
return result;
}
Get the values like this, in embed.js:
var value1 = parseGet('q');
value1 should then be "123".
I think you can't,but you can declare all param before required your js file same as:
<script type="text/javascript">
var q = 123;
var parameter1 = 450;
var parameter2 = 300;
</script>
<script src="http://example.com/embed.js"></script>
You could place the parameters in attributes of the <script> tag.
<script src="http://example.com/embed.js" q="123" parameter1="450" parameter2="300"></script>
You can access these parameters in embed.js with
document.currentScript.getAttribute('q');
document.currentScript.getAttribute('parameter1');
document.currentScript.getAttribute('parameter2');
Note: document.currentScriptdoes not work on IE.
For more info check this out.
You can access script tag as the last script tag if ask for it without waiting for document load.
~function() {
var s = document.querySelectorAll("script");
s = s[s.length-1];
console.log(s.src);
}();

Is there a restriction on using JSP tags inside Javascript?

Is there some restrictions on using JSP tags inside a javascript?
I have a script like this:
<script>
<%int ccCount = 0;%>
var stockData = new Array();
for (var i = 0; i < <%=sNum%>; i++)
{
stockData[i] = {Supplier: "<%=sName[ccCount]%>", CC: <%=cc[ccCount]%>};
<%ccCount++;%>
}
<script>
Every line inside JSP tags worked, except the <%ccCount++;%>. My sName and cc array kept pointing to the first index (0), can anyone tell me what went wrong and how can I fix it?
Thank you.
The JSP is executed on the server. It ten send the resulting Javascript to the browser, where this part is executed.
What JSP/Java sees:
int ccCount = 0;
=sName[ccCount];
=cc[ccCount]%>};
ccCount++;
The resulting JavaScript is ( assumed cc[ccCount] would be 42 and sNum 12345)
<script>
var stockData = new Array();
for (var i = 0; i < 12345; i++)
{
stockData[i] = {Supplier: "some value", CC: 42};
43
}
<script>
As the JSP is executed on the sevrer, it's not part of the for-loop which is only existing in the browser.

Parse all values from a XML element using Google Apps Script?

I am trying to parse forex values (all of them) for http://indicador.eof.cl/rss XML feed into a Gooogle Sites trough Google Apps Script.
The script as follow>
function doGet(){
var response = UrlFetchApp.fetch("http://indicador.eof.cl/rss").getContentText();
var parsedResponse = Xml.parse(response, false);
var root = parsedResponse.getElement();
var entries = root.getElement('channel').getElements("item");
for (var i=0; i<entries.length; i++) {
var e = entries[i];
var title = e.getElement("title").getText();
var description = e.getElement("description").getText();
}
var app = UiApp.createApplication();
var TopVar = app.createHorizontalPanel();
TopVar.add(app.createLabel(title).setStyleAttribute("fontSize","12px"));
TopVar.add(app.createLabel(description).setStyleAttribute("fontSize","12px"));
app.add(TopVar);
return app;
}
The issue is the code just bring me the first value no all of them, what i am forgetting?
Best Regards,
Try to move TopVar.add(...); lines inside for loop :
var app = UiApp.createApplication();
var TopVar = app.createHorizontalPanel();
for (var i=0; i<entries.length; i++) {
var e = entries[i];
var title = e.getElement("title").getText();
var description = e.getElement("description").getText();
TopVar.add(app.createLabel(title).setStyleAttribute("fontSize","12px"));
TopVar.add(app.createLabel(description).setStyleAttribute("fontSize","12px"));
}
Actually, I know nothing about google-apps-script. But your current code logic seems a bit off. It doesn't make use of values of local variables declare inside for loop (e, title, and description). Value of those variables changed in every iteration without any code using it.

Categories

Resources