how to write Html script tag in vue js - html

I have html file which has 3 script tags. I want to put these script tags in my vue.js file.
i have added the html div element to by vue js file and it is getting rendered. but i am just not able to load script from html into vue.
Below is my html file.
<html>
<body>
<script type="text/javascript">
mxBasePath = "../editors/pure";
</script>
<script type="text/javascript" src="../editors/pure/js/mxClient.js"></script>
<script src="../editors/dist/main.js"></script>
</body>
</html>
I have tried to add my scripts in the mounted section of vue. Below is my vue.js file
import * as client from '../editors/pure/js/mxClient.js'
import * as mains from '../editors/dist/main.js'
mounted () {
var z = document.getElementById('geApp')
let recaptchaScript = document.createElement('script')
recaptchaScript.setAttribute('src', client)
z.appendChild(recaptchaScript)
let processes = document.createElement('script')
processes.setAttribute('src', mains)
z.appendChild(processes)
let basepath = document.createElement('script')
basepath.innertext = 'mxBasePath = "../editors/pure"'
z.appendChild(basepath)
},
But i am getting the error as file not found.. I solved the problem by importing the src file but now i am getting the error as "one of the functionality is not defined."
Please can anyone help me in adding the scripts to vue.js file

Related

Updating automatically an HTML content when the imported *.json values are changed

I have an HTML code that imports a LOCAL but UPDATABLE *.json content, and it must be updated automatically when the *.json file is updated.
This is the *.HTML code:
<html>
<head>
<script type="text/javascript" src="sample.json"></script>
<script type="text/javascript" >
function load() {
setInterval(function () {
var mydata = JSON.parse(data);
var div = document.getElementById('data');
div.innerHTML = mydata[0].location.altitude;
}, 100);}
</script>
</head>
<body onload="load()">
<div id="data">
</div>
</body>
</html>
and the adapted sample.json file is:
data = '[{"location": {"altitude": 40}}]';
I just wanna see the altitude is changing in the browser(HTML) whenever the sample.json file is updated.
Now the HTML works but only ONCE, I wanna make it dynamic.
What should I do to make the function setInterval work correctly? or maybe this function works only for local changes, not external ones.
Thnks, Sadeq
If you want the browser to get data from a URL even interval, then you need to write code which gets data from a URL in the interval. e.g. with the Fetch API. (At which point you should make it JSON instead of JS).
However HTTP is not fast. You do not want to be polling over HTTP every 100ms. Consider using Websockets to push the data from the server when it changes instead of polling.

Load graph from json using JointJS

I'm having a problem trying to load a graph form json using JointJS. I know the theory (https://resources.jointjs.com/tutorial/serialization), however, I still do not know how to show a graph.
This is my html file:
<!-- JointJS libraries omitted for space -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
function read_json() {
$.getJSON("/jointsjdemo/demo.json", function(data) {
var graph = new joint.dia.Graph;
graph.fromJSON(data);
var paper = new joint.dia.Paper({
el: document.getElementById('myholder'),
model: graph,
width: 600,
height: 100,
gridSize: 1
});
});
}
read_json();
</script>
And this is my json file:
{"cells":[{"type":"standard.Rectangle","position":{"x":100,"y":30},"size":{"width":100,"height":40},"angle":0,"id":"42a7f123-1f0d-4d06-b49e-8cbcbbb17e23","z":1,"attrs":{"body":{"fill":"blue"},"label":{"fill":"white","text":"Hello"}}},{"type":"standard.Rectangle","position":{"x":400,"y":30},"size":{"width":100,"height":40},"angle":0,"id":"6ecac186-b9c1-4755-97db-704cd9b9156f","z":1,"attrs":{"body":{"fill":"blue"},"label":{"fill":"white","text":"World!"}}},{"type":"standard.Link","source":{"id":"42a7f123-1f0d-4d06-b49e-8cbcbbb17e23"},"target":{"id":"6ecac186-b9c1-4755-97db-704cd9b9156f"},"id":"fa23e165-3c9f-46f8-9fe9-e6660d4086ca","z":2,"attrs":{}}]}
When a load the web page, it shows nothing on screen. I'm deployed my app in Apache Tomcat. Using Chrome Developer Tools, no errors are shown in Console.
I dont know what I'm missing.
Any help please? The json file was generated through toJSON command.
P.D. I think it should be better to hire someone, but I'm still trying to do this.

application can't find a .js file

I have a Play application. The UI of the application is in Angular. I have created a folder ui which is the top level Angular directory.
build.sbt
`ui-dev-build` := {
implicit val UIroot = baseDirectory.value / "ui"
if (runDevBuild != Success) throw new Exception("Oops! UI Build crashed.")
}
def runDevBuild(implicit dir: File): Int = ifUiInstalled(runScript("npm run build"))
package.json
"build": "ng build --output-path ../public/ui",
When the Angular application is build, I transfer the output to the public folder of the Play framework. From there, Play transfers the contacts of the public folder to target folder for deployment. In the index.html (homepage html file), I access angular by including the scripts created in Angular build.
<script src="#routes.Assets.versioned("ui/runtime.js")" type="text/javascript"></script>
<script src="#routes.Assets.versioned("ui/vendor.js")" type="text/javascript"></script>
<script src="#routes.Assets.versioned("ui/styles.js")" type="text/javascript"></script>
<script src="#routes.Assets.versioned("ui/main.js")" type="text/javascript"></script>
<script src="#routes.Assets.versioned("ui/scripts.js")" type="text/javascript"></script>
This works fine.
I want to use ng-ace2-editor in my application - https://github.com/fxmontigny/ng2-ace-editor. I have added it in package.json - "ng2-ace-editor": "0.3.9" and I can see that ng2-ace-editor directory is present in node_modules.
When I run the application, I get error
GET http://localhost:9000/mode-html.js net::ERR_ABORTED 404 (Not Found)
exports.loadScript # index.js:3802
exports.loadModule # index.js:4174
setMode # index.js:10152
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.setMode
I can't understand how to make my application find mode-html.js. The file is present at location "./node_modules/ace-builds/src-min/mode-html.js. I have added this path in "script":[] of package.json but I still get the error.
"scripts":[
"./node_modules/ace-builds/src-min/ace.js",
"./node_modules/ace-builds/src-min/theme-eclipse.js",
"./node_modules/ace-builds/src-min/mode-html.js"
]
Interestingly, things work if I include ace.js in the homepage file
<script src="#routes.Assets.versioned("ui/runtime.js")" type="text/javascript"></script>
<script src="#routes.Assets.versioned("ui/vendor.js")" type="text/javascript"></script>
<script src="#routes.Assets.versioned("ui/styles.js")" type="text/javascript"></script>
<script src="#routes.Assets.versioned("ui/main.js")" type="text/javascript"></script>
<script src="#routes.Assets.versioned("ui/scripts.js")" type="text/javascript"></script>
<script src="#routes.Assets.versioned("javascripts/common/vendor/ace/src-min/ace.js")" type="text/javascript"></script> <!-- this makes things work-->
So I know that issue is that my mode-html.js file is not getting served and most likely it is the path resolution issue but I can't figure out what is it.
Further analysis shows that the following code in ace.js causes the error.
exports.loadModule = function(moduleName, onLoad) {
var module, moduleType;
if (Array.isArray(moduleName)) {
moduleType = moduleName[0];
moduleName = moduleName[1];
}
try {
module = require(moduleName);
} catch (e) {}
if (module && !exports.$loading[moduleName])
return onLoad && onLoad(module);
if (!exports.$loading[moduleName])
exports.$loading[moduleName] = [];
exports.$loading[moduleName].push(onLoad);
if (exports.$loading[moduleName].length > 1)
return;
var afterLoad = function() {
require([moduleName], function(module) {
exports._emit("load.module", {name: moduleName, module: module});
var listeners = exports.$loading[moduleName];
exports.$loading[moduleName] = null;
listeners.forEach(function(onLoad) {
onLoad && onLoad(module);
});
});
};
if (!exports.get("packaged"))
return afterLoad();
net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad);
reportErrorIfPathIsNotConfigured();
};
var reportErrorIfPathIsNotConfigured = function() {
if (
!options.basePath && !options.workerPath
&& !options.modePath && !options.themePath
&& !Object.keys(options.$moduleUrls).length
) {
console.error(
"Unable to infer path to ace from script src,",
"use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes",
"or with webpack use ace/webpack-resolver"
);
reportErrorIfPathIsNotConfigured = function() {};
}
};
Why does explicitly calling <script src="#routes.Assets.versioned("javascripts/common/vendor/ace/src-min/ace.js")" type="text/javascript"></script> make the code work. Should this script be already available in ui/scripts.js as per Angular packaging method https://upgradetoangular.com/angular-news/the-angular-cli-is-a-great-way-to-build-your-angular-app-but-what-it-does-can-be-a-mystery-what-are-those-files-it-generates/?
I finally was able to make my code work. My setup is different. I build my Angular application and the it is served from my Play server. The angular build is stored in Play's /public/ui folder. The requests should be in format /assets/ui/.. which gets mapped to /public/ui/... due to a rule in Play routes file
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
When I ran the code, I got error.
Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:9000/worker-javascript.js' failed to load.
at blob:http://localhost:9000/3df21e42-fecb-4026-8bd6-f2b0d1d0540a:1:1
Earlier, I also got error Unable to infer path to ace from script src, use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes or with webpack use ace/webpack-resolver
It seems ng-ace-editor imports .js scripts (theme, mode, worker) based on the theme and mode of the editor. The theme and mode js files can be included in scripts.js but some worker-.js files can't be (I don't know why, maybe because worker ones are loaded dynamically using importScript.
The scripts section in Angular.json is (this will all get bundled in scripts.js in Angular's final bundle)
"scripts": [
"./node_modules/ace-builds/src/ace.js",
"./node_modules/ace-builds/src/theme-eclipse.js",
"./node_modules/ace-builds/src/theme-monokai.js",
"./node_modules/ace-builds/src/mode-html.js"
]]
To include worker-.js files, I added this rule because it seems angular-cli can't load from node_modules. So I had to copy the files from node modules to root of my ui build - How to include assets from node_modules in angular cli project
"assets": [
"src/assets",
"src/favicon.ico",
{
"glob": "**/*",
"input": "./node_modules/ace-builds/src/",
"output": "/"
}
],
When I executed the code, I found error that http://localhost:9000/worker-javascript.js can't be loaded. I realised that my files are loaded in /assets/ui/ path and not in the server's root directory. So I set the basepath to /assets/ui in the component's .ts file
import * as ace from 'ace-builds/src-noconflict/ace';
ace.config.set('basePath', '/assets/ui/');
ace.config.set('modePath', '');
ace.config.set('themePath', '');
In summary
basePath seem to be what is used to load scripts dynamically (eg worker scripts)
modePath and themePath are / as the mode and theme scripts are bundled in scripts.js and are available at root level
need to copy worker-.js files outside node_modules as angular_cli can't copy assets from node_modules

populating a DataTable with a JSON file directly, or querying a local spreadsheet (google visualization)

I am looking for the easiest way to populate a data table in google visualizations using either a json file or a local spreadsheet(.xlsx).
heres my code:
<!DOCTYPE html>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable.fromJSON(sampleData.json,0.6);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Heres my json file:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
When I run my code in my browser, I get
"Uncaught ReferenceError: sampleData is not defined"
Anyone know how I can make this work?
Thanks in advance
You COULD simply place the contents of your JSON file right inline there in your HTML where the string "sampleData.JSON" is. That is, take out "sampleData.JSON" and replace it with the entire contents of your JSON file. I'm pretty sure you'll make some progress if you do this.
Try putting sampleData.json in quotes, assuming that the filename is sampleData.json and is in the same folder as your HTML.
var data = new google.visualization.DataTable.fromJSON('sampleData.json',0.6);

refresh data read from text file with out page refresh

i am a novice at Java and JS so this will be very basic.
I've got this code that creates a text file in a specific directory. i only got as far as creating an actuale file, however, as the text file will be frequantely updated, i need the page to refresh/reload the text file and display it's data (just in the blank page). How do i do this, with out user needed to click refresh (auto refresh in sense, however, i've tried auto refresh and it does not seem to reload JS and/or display text file's content)
Create Text file/Read/Display content/Refresh and/or Reload - no user refresh
<script>
function createFile()
{
var object = new ActiveXObject("Scripting.FileSystemObject");
var file = object.CreateTextFile("C:/Documents and Settings/galimbek.sagidenov/My Documents/Practice HTML_Photoshop_java/BroadcastTest.txt", false);
file.WriteLine('Hello World');
file.WriteLine('Hope is a thing with feathers, that perches on the soul.');
file.Close();
}
</script>
this will not accomplished by using client side javascript only you have to use server side code:
server ex (using node.js):
server :
var http = require("http"),
fs=require("fs");
http.createServer(function(request, response) {
fs.writeFileSync("C:/Documents and Settings/galimbek.sagidenov/My Documents/Practice HTML_Photoshop_java/BroadcastTest.txt", 'Hello World\r\nHope is a thing with feathers, that perches on the soul.');
}).listen(8888);
client
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(function(){
$.get("http://localhost:8888",function(){
console.log("writing to file successeded");
})
})
</script>