How to load local text information into <div> section - javascript

I am trying to draw a diagram by using below codes.
It works well.
As you can see, I should put some text information in the div.
If there is a sample.txt which includes this information in local drive, can I load it into div section dynamically instead of putting it manually?
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sample Diagram</title>
</head>
<body>
<div class="diagram">
Title: Diagram
<!-- Participant FIRST
Participant SECOND
Participant D
Participant F
Participant G //-->
E->F: 2
SECOND->FIRST: 1
FIRST->SECOND: 1
C-->SECOND: Request token
C->E: 2
SECOND->FIRST: Forward request
FIRST->>C: Send token
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/js-sequence-diagrams/1.0.4/sequence-diagram-min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
UPDATE
/test/index.html
/test/js/index.js
/test/js/sample.txt
/test/sample.txt
index.js
// js-sequence-diagrams by bramp <http://bramp.github.io/js-sequence-diagrams/>
$(".diagram").sequenceDiagram({theme: 'simple'});
$(function(){
$.get("sample.txt", function(data) {
$(".diagram").text(data);
});
});
sample.txt
Title: Diagram
SECOND->FIRST: 1
FIRST->SECOND: 1
C-->SECOND: Request token
C->E: 1
SECOND->FIRST: Forward request
FIRST->>C: Send token
Without inner text
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sample Diagram</title>
</head>
<body>
<div class="diagram">
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/js-sequence-diagrams/1.0.4/sequence-diagram-min.js'></script>
<script src="js/index.js"></script>
</body>
</html>

Add a file-input element to the HTML page:
<input type="file" id="file" onchange="readTxT()"/>
And select sample.txt manually:
function readTxT(){
var reader = new FileReader();
var files=document.getElementById('file').files;
var f = files[0];
reader.onload = function(e) {
var text = reader.result;
$(".diagram").text(text).sequenceDiagram({theme: 'simple'});
}
reader.readAsText(f);
}

The simplest and easy way is to make get request to the server. And for that you have to use jQuery $.get function. Which will make a request for you.
Here is reference to jQuery.get()
USAGE
// make sure the PATH is correct for `sample.txt`
// $.get(your URL to the file, callback function)
$(function(){
$.get("sample.txt", function(data) {
$(".diagram").text(data);
});
});

If the sample.txt is available on the (http) server the site is hosted with (may be localhost), yes.
Assuming your directory structure is like this (/var/www/ is the server's root directory in my example):
/var/www/
index.html (The file without the diagram content)
sample.txt
js/
index.js
Place this in your index.js:
window.onload = function() {
$.get("sample.txt", function(data) {
$(".diagram").text(data).sequenceDiagram({theme: 'simple'});
});
}
If you're not using any HTTP server, you can't load files from the file system directly - that's part of the Javascript sandbox (security concept).
I would then recommend using something like in lx1412's answer, a manual file chooser is the only way how this could work then.
I've tested the script above using Firefox and an HTTP server; and my edit of lx1412's answer using Firefox without an HTTP server.

Related

How to execute an external html/javascript file

The scenario for my frontend javascript application is as following:
GET via URL an html/javascript file
execute it
Current I am trying the following frontend approach:
const myElement = document.createElement('myElement');
myElement.setAttribute('src', 'https://.../file.html');
document.body.appendChild(myElement);
And file.html looks like:
<html>
<head>
<script language="Javascript">
function doSomething() { }
</script>
</head>
<body onload="doSomething()"></body>
</html>
But nothing is happening.
Am I wrong to expect that on document.body.appendChild() , the file will be downloaded and executed as if the URL was opened from the browser?

Django load text file into html file using jquery

I want to implement this example code from w3schools.com using Django. The code loads a text file into a html file using the jquery load() function. The code looks like this
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt");
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
My question is now, how do I store my text file such that the load function has access to it in my Django project?
Put the 'demo_test.txt' in your static folder and make sure to specify your static url in settings. Let's say your static url is "cdn" pointing to folder "static". In that case you could use $("#div1").load("/cdn/demo_test.txt");
In settings.py:
STATIC_URL = '/cdn/'
STATIC_ROOT = '/path/to/your/static'

javascript not working from network drive

I'm trying to run the below file. It runs perfectly fine when I run it on a local drive but if I place it on a network drive it no longer works. Any idea why this might be?
The below is code that I am trying to run. It is using pivottable from here: https://github.com/nicolaskruchten/pivottable.
<!DOCTYPE html>
<html>
<head>
<title> Demo</title>
<!-- external libs from cdnjs -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<!-- PivotTable.js libs from ../dist -->
<link rel="stylesheet" type="text/css" href="../dist/pivot.css">
<script type="text/javascript" src="../dist/pivot.js"></script>
<style>
body {font-family: Verdana;}
</style>
<!-- optional: mobile support with jqueryui-touch-punch -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
</head>
<body>
<script type="text/javascript">
// This example shows custom aggregators using
$(function(){
var tpl = $.pivotUtilities.aggregatorTemplates;
$.getJSON("col.json", function(frontier) {
$("#output").pivotUI(frontier, {
rows: ["Manager"], cols: ["Sector"],
aggregators: {
"Number of Positions": function() { return tpl.count()() },
"Manager Weight": function() { return tpl.sum()(["Port"])},
"Benchmark XGCC Weight": function() { return tpl.sum()(["Bench"])},
}
});
});
});
</script>
<div id="output" style="margin: 30px;"></div>
</body>
</html>
File:/// urls will run in a different context than HTTP/HTTPS and other contexts (internal, public, private, unsafe). What limitations in question depend on the specific browser, the OS and the context itself.
If you must execute JavaScript within HTML, the safest and most assured way to run is to have it running via a web server.
Also worth noting, there are a few local/relative files. ../dist/pivot.js and ../dist/pivot.css are you sure you're saving those files, and they are in the correct relative path as well?

AngularJS error while using ngAudio

I am trying to play audio using AngualarJs
My HTML CODE:
<!doctype HTML>
<html>
<head>
</head>
<body ng-app="test" ng-controller="audioTest">
<button ng-click="playSound()"></button>
<script src="javascripts/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script src="javascripts/angular.audio.js"></script>
<script src="app.js"></script>
</body>
</html>
My app.js Code:
var app = angular.module("test",['ngAudio']);
var audio = app.controller("audioTest",function($scope,ngAudio){
$scope.playSound = function(){
$scope.audio = ngAudio.load("abc.wav");
$scope.audio.play();
}
});
While i load page i got error in console which lead me to
Error Details
The error you're reporting is due to an error resolving angular.audio.js script that can't be found by the name javascripts/angular.audio.js
I made a working fiddle: http://jsfiddle.net/en8x1nny/
This fiddle imports the script that the original demo from ngAudio is using.
The full path for that script is: http://danielstern.github.io/ngAudio/angular.audio.js.
You can download it and add it to your javascripts directory. Be sure not to use it by the URL mentioned above because github is not a CDN intended to serve scripts.
If you previously installed ngAudio by bower, the script should be in:
your_project_path/bower_components/angular-audio/app/angular.audio.js

Trying to use youtube api on html page

Here is my code:
<!DOCTYPE html>
<html lang="en" >
<head>
<script type="text/javascript">
function showResponse(response){
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad(){
gapi.client.load('youtube','v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad(){
gapi.client.setApiKey('MyActualKey');
search();
}
function search(){
var request = gapi.client.youtube.search.list({
part: 'snippet'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response){
showResponse(response);
}
</script>
<title></title>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
</head>
<body>
<div id="response"></div>
</body>
</html>
This code is from Codecademy, and I thought I can use it on an html page and it would work.
I got an API key from google and I set my Youtube data api v3 setting to enabled in my google developers console, but this code gives me a blank page.
What am I doing wrong?
There are a few missing pieces, code snippets which codecademy likely took for granted but which are essential when placing it in your own server outside of their app. First of all, you need a line that actually loads the gapi library from google. You can put this in your code, just before the closing :
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
In short, this will get the library from Google's servers, and when it's loaded the library will automatically call your onClientLoad method, kicking off your app.
Next, you say you have an API key; make sure you put that key into your code by replacing this:
gapi.client.setApiKey('MyKey');
with this:
gapi.client.setApiKey('{WHATEVER_YOUR_ACTUAL_KEY IS');
Finally, as the commenters mentioned, your body is empty, so when your code executes the showResponse method there's no place to put what comes back. Add this:
<div id="response"></div>

Categories

Resources