Run a script only after another one completes - javascript

I have multiple scripts in my HTML header. the two of concern are as follows:
1) JS script ('Infected Data') produces an object with data. The data is retrieved and computed from a google scripts file, so naturally it takes a bit.
2) A script which generates a map. The map is color coded depending on the values of the Infected Object Data.
The problem is the map loads before i can get the object, so it is not colored.
Map should look like this:
Map looks like this:
HTML Header:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>JQVMap - World Map</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link href="../dist/jqvmap.css" media="screen" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../dist/jquery.vmap.js"></script>
<script type="text/javascript" src="../dist/maps/jquery.vmap.world.js" charset="utf-8"></script>
<script type="text/javascript" src="js/jquery.vmap.sampledata.deaths.js"></script>
<script type="text/javascript" src="js/jquery.vmap.sampledata.infected.js"></script>
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#ffffff',
hoverOpacity: 0.8,
selectedColor: '#3498DB',
enableZoom: true,
showTooltip: true,
scaleColors: ['#F3A291', '#FF4F3B'],
values: infected_data,
normalizeFunction: 'polynomial',
onLabelShow: function(event, label, code)
{
// Remove for Russian Joke
/*if (code == 'ru')
{
// Plain TEXT labels
label.text('Bears, vodka, balalaika');
}
else*/
label.html('<div class="map-tooltip"><h1 class="header">'+label.html()+'</h1><p class="description">Infected: '+infected_data[code]+'</p><p class="description">Deaths: '+death_data[code]+'</p></div>');
/*else if (code == 'us')
{
label.html(label.html()+' (GDP - '+sample_data[code]+')');
}*/
},
/*onRegionOver: function(event, code)
{
if (code == 'ca')
{
event.preventDefault();
}
}, */
});
});
</script>
</head>
Infected Data JS FIle:
var infected_dataINT = {};
var infected_data = {};
const url = "https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec";
// Declare an async function
const getData = async () => {
// Use the await keyword to let JS know this variable has some latency so it should wait for it to be filled
// When the variable is fetched, use the .then() callback to carry on
const DataJSON = await fetch(url).then(response =>
response.json()
)
return await DataJSON
};
console.log(getData());
getData().then(result => {
console.log(result);
infected_dataINT = result;
console.log(infected_dataINT);
function toString(o) {
Object.keys(o).forEach(k => {
if (typeof o[k] === 'object') {
return toString(o[k]);
}
o[k] = '' + o[k];
});
return o;
}
console.log(toString(infected_dataINT));
infected_data = toString(infected_dataINT);
})
How can i slow down the jQuery(document).ready(function () {.... to run only after <script type="text/javascript" src="js/jquery.vmap.sampledata.infected.js"></script> has ran

You can dynamically append the script element to the document after the response has been recieved from the server like this:
let script = document.createElement('script');
script.src = 'myJqueryFile.js';
document.head.appendChild(script);
You just have to put those jquery codes inside a .js file.

Sounds like an asynch problem...
Where do you close the header?
</head>
And where is your onload event to synchrinise things?
<body onload="Function_That_KickStarts_Everything();">

Please use the correct document structure and ensure everything begins with the ONLOAD event so that 3rd party libraries may all load and synchronize... follow this please:
<html>
<head>
<style type="text/css">
</style>
</head>
<body onload="Function_That_KickStarts_Everything();">
<script src="Third_Party_Library_1.js"></script>
<script src="Third_Party_Library_2.js"></script>
<script type="text/javascript">
</script>
</body>
</html>

Related

How to update html document using feather js?

I have a service that I call after every 5 secs to return data from postgres table, now I want this data to be displayed on html document
app.js
const stats=app.service('test_view');
// console.log(stats);
function getstats(){
stats.find().then(response=>{
console.log('data is ',response.data)});};
setInterval(function() {
getstats();
}, 5000);
// console.log(stats);
stats.html
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
Everything is running fine and I am getting results in console, I am using feather.js now I want these results to be displayed in div tag of html.Please help me in this regard.
You need to call the feathers service from the browser. You can do this a number of different ways (as a REST call, with the feathers client, etc.).
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/core-js/2.1.4/core.min.js"></script>
<script src="//unpkg.com/#feathersjs/client#4.0.0-pre.3/dist/feathers.js"></script>
<script src="//unpkg.com/axios/dist/axios.min.js"></script>
<script>
// #feathersjs/client is exposed as the `feathers` global.
const app = feathers();
app.configure(feathers.rest('http://localhost:3000').axios(axios));
app.service('test_view').find();
})
.then(data => {
// do something with data
});
</script>
</head>
<body></body>
</html>
A lot of this depends on what (if anything) you're using for your front-end implementation. This sets up a minimal feathersjs/client using axios for REST, with no authentication, and calls your service (on port 3000) and gets the payload.
To do this every 5 seconds is outside the scope of feathers and up to how you build your web app.
Here is a working example of how you could change the contents of that div when you get data back from your remote call.
// Simulate your remote call... ignore this part.
const stats = {}
stats.find = () => new Promise((resolve, reject) => resolve({
data: 'here is some data ' + new Date().toLocaleTimeString('en-US')
}));
// Div you want to change.
const resultsDiv = document.getElementById('stats');
// Get the data
function getstats () {
stats.find().then(response => {
console.log('data is ', response.data);
// Update the contents of the div with your data.
resultsDiv.innerHTML = response.data;
});
}
setInterval(function() {
getstats();
}, 1000);
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>

Some HTML nodes are not created while I execute function.Cannot read property 'childNodes' of null,

Why I am getting this error? I guess some of my HTML nodes are not created why I try to call the doSearch method. It's actually happening only second time I call this function.
I'm using React and calling this function inside componentDidUpdate lifecycle method.
Here is my HTML file where I load my script inside
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="//csr.inspsearchapi.com/lib/infospace.search.js">
</script>
<link rel="stylesheet" href="./static/style/styles.css" />
</head>
<body>
<div class="container"></div>
<script src = "bundle.js"></script>
</body>
Here is my function:
componentDidUpdate(prevProps) {
const signature = this.props.signature ? this.props.signature.response.data : '';
window.insp.search.doSearch({
query: this.state.searchText,
searchUrlFormat: this.state.searchText,
signature,
page: 1,
containers: {
'top': {id:'topResults'},
'related': {id:'relatedResults'},
},
});
}

Difficulties running JavaScript (from .js file) in an Angular application

I am trying to incorporate a Javascript function (contained in app.js), which I am trying to run from the index.html of my Angular 2 application.
Initially I used a CLI program called Office Add-in generator to make a non-angular application, in which this JavaScript works.
However when using the Add-in generator in an Angular application the app.js file is not automatically generated. Manually copy pasting the app.js file and <script> link does not work either. I realise I have only provided a couple of files worth of code, let me know if I should edit more in, or provide a github link?
The error in chrome is net::ERR_ABORTED not defined with a 404 message. (relating to the app.js file)
~~~~HTML~~~~~
<head>
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.css">
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.components.css">
<meta charset="utf-8">
<title>Microsoft Graph Connect sample</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>
<script>
window.history.replaceState = function(){};
window.history.pushState = function(){};
</script>
</head>
<body>
<app-root></app-root>
<button onclick="setItemBody()">Paste to email</button>
<script type="text/javascript" src="node_modules/core-js/client/core.js"></script>
<script type="text/javascript" src="node_modules/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="node_modules/office-ui-fabric-js/dist/js/fabric.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
~~~~~~~app.js~~~~~~~~
var item;
Office.initialize = function () {
item = Office.context.mailbox.item;
// Checks for the DOM to load using the jQuery ready function.
$(document).ready(function () {
// After the DOM is loaded, app-specific code can run.
// Set data in the body of the composed item.
// setItemBody();
});
}
// Get the body type of the composed item, and set data in
// in the appropriate data type in the item body.
function setItemBody() {
item.body.getTypeAsync(
function (result) {
if (result.status == Office.AsyncResultStatus.Failed){
write(result.error.message);
}
else {
// Successfully got the type of item body.
// Set data of the appropriate type in body.
if (result.value == Office.MailboxEnums.BodyType.Html) {
// Body is of HTML type.
// Specify HTML in the coercionType parameter
// of setSelectedDataAsync.
item.body.setSelectedDataAsync(
'<b>These are the times I am available:</b><br>Monday -- 8:30 to 9:00<br>Tuesday -- 1:00 to 5:00<br>Thursday -- 4:00 to 5:00<br>',
{ coercionType: Office.CoercionType.Html,
asyncContext: { var3: 1, var4: 2 } },
function (asyncResult) {
if (asyncResult.status ==
Office.AsyncResultStatus.Failed){
write(asyncResult.error.message);
}
else {
// Successfully set data in item body.
// Do whatever appropriate for your scenario,
// using the arguments var3 and var4 as applicable.
}
});
}
else {
// Body is of text type.
item.body.setSelectedDataAsync(
' Kindly note we now open 7 days a week.',
{ coercionType: Office.CoercionType.Text,
asyncContext: { var3: 1, var4: 2 } },
function (asyncResult) {
if (asyncResult.status ==
Office.AsyncResultStatus.Failed){
write(asyncResult.error.message);
}
else {
// Successfully set data in item body.
// Do whatever appropriate for your scenario,
// using the arguments var3 and var4 as applicable.
}
});
}
}
});
}
// Writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
Actually you should not just put your js files in index.html better add in .angular-cli.json file.. and about js not working in ng2+ project.. check out https://angular.io/guide/attribute-directives I think you must make wrapper. check this as well https://medium.com/#NetanelBasal/typescript-integrate-jquery-plugin-in-your-project-e28c6887d8dc

Search for word and color it

I am trying to search for a word in iframe and color it using angularjs and jquery. For jquery code i took help from #andrew stackoverflow.
In Jquery code if condition is there, controller is not going inside if condition. please help me to solve the problem.
Here is my complete code, which contains angular code and jquery code.
Angular code is working just fine, in the console i am able to see all the consoles, first i am parsing the arrays and taking out only the string required to search in the jquery. After that i am using that search word to search in the the iframe. But i am facing some problem with the jquery code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html ng-app="app">
<head>
<title>
<%=t itle %>
</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
</head>
<body>
<div ng-controller="ToddlerCtrl">
<h2>Sample</h2>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script type="text/javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<iframe src="text.txt" id="myIframe"></iframe>
<script type="text/javascript">
var myApp = angular.module('app', []);
myApp.controller('ToddlerCtrl', function($scope) {
// Define an array of Toddler objects
$scope.toddlers = [
[100, ["sample"]],
[100, ["used"]],
[100, ["tag"]],
[33.33333333333334, ["file"]]
];
for (var key in $scope.toddlers) {
if ($scope.toddlers.hasOwnProperty(key)) {
var temp = JSON.stringify($scope.toddlers[key][1])
var final_string = temp.slice(2, -2);
var searchWord = final_string;
// console.log(searchWord)
$(document).ready(function() {
$('#myIframe').ready(function() {
var $html = $($('#myIframe').contents().find('body').html());
if ($html.contents().text().search(searchWord) != -1) {
// Some problem with the if condition i guess.
// Controller is not entering if condition.
var replaceWith = "<span style='color:red'>" + searchWord + "</span>"
var newHTML = $html.text().replace(searchWord, replaceWith);
$('#myIframe').contents().find('body').html(newHTML);
}
});
});
// alert($scope.toddlers[key][1]);
// console.log("searchWord")
}
}
});
You can do it easily with Jquery, you can use this function on Javascript:
function findAndColorWord(html, word, color){
var indexWordStart = html.indexOf(word);
var wordLength = word.length;
var coloredWord = '<span style="color: '+color+'">'+word+'</span>';
var firstHtmlPart = html.substring(0, indexWordStart - 1);
var secondHtmlPart = html.substring(indexWordStart + wordLength, html.length - 1);
return firstHtmlPart + coloredWord + secondHtmlPart;
}
You only need to get the position of the word in the html of the iframe, that you can get with $("#id-of the iframe")[0].outerHTML , and after insert in that position a span element with the colored style for the word.
I maked a basic example with a Div that works in the same way that with an a iframe, you can see the example here:
https://jsfiddle.net/9zt976uz/2/#&togetherjs=nQoh3LINQG

google visualization datatable not going to csv

Been messing around with this on google playground, and it appears to work without any errors. However when I go to do the export options it doesn't give me anything. Any idea?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Name', 'Height', 'Smokes'],
['Tong Ning mu', 174, true],
['Huang Ang fa', 523, false],
['Teng nu', 86, true]
]);
var options = { 'showRowNumber': true };
options['page'] = 'enable';
options['pageSize'] = 3;
options['pagingSymbols'] = { prev: 'prev', next: 'next' };
options['pagingButtonsConfiguration'] = 'auto';
var components = [
{ type: 'html', datasource: data },
{ type: 'csv', datasource: data }
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, options);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="table"></div>
<dov id="toolbar_div"></div>
</body>
</html>
​
According to the documentation you have to pass the data through a URL and not any hand-populated data objects. See:
https://developers.google.com/chart/interactive/docs/gallery/toolbar
Usage
To use a toolbar, your visualization must get its data from a URL; you cannot pass in hand-populated DataTable or DataView objects. You will pass the URL of the data used to populate your visualization into the drawToolbar() method.
Code:
$('#Export').click(function () {
var csvFormattedDataTable = google.visualization.dataTableToCsv(data);
var encodedUri = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvFormattedDataTable);
this.href = encodedUri;
this.download = 'table-data.csv';
this.target = '_blank';
});
Explanation:
Check my answer posted here for an explanation of the code. Export is the Id of the anchor element on the page with the download option.

Categories

Resources