How To Run JS Files In Web Server Directory - javascript

I'm new to Javascript,
When I have these two files in one directory in Desktop, It works fine,
But when i put them in the Web Server Directory /var/www/html it doesn't work
I know JS is a client side thing, but if we are building a website these .js files will be in some web server directory and should work while they are placed there
I use apache 2.4 on ubuntu 20.4
Javascript.js code :
/*global document, console */
var mybtn = document.getElementById("mybtn");
var mydiv = document.getElementById("mydiv");
var myid = document.getElementById("myid");
mybtn.onclick = function(){
console.log(myid.value);
mydiv.innerHTML = myid.value;
}
.html code:
<html>
<head></head>
<body>
<input type="text" id="myid">
<button id="mybtn">click</button>
<div id="mydiv"></div>
<script src="javascript.js">
</script>
</body>
</html>

Let's assume this is your public_html directory /var/www/html and for better code organization create a directory for javascript files as js You can do this for CSS, images and so on. So Your public directory become like this
public_html
js
myjscodehere.js // copy your javascript code to this file.
css
images
index.html
As for the index.html. Set a directory path to your javascript file.
<html>
<head></head>
<body>
<input type="text" id="myid">
<button id="mybtn">click</button>
<div id="mydiv"></div>
<script type="text/javascript" src="/js/myjscodehere.js"></script>
</body>
</html>
Your javascript files will work on client-side upon sending a get request to your web-server using Chrome, Mozilla and on
Separation of js code gives you many benefits such as caching to your js files and better organization if you are building a larger project it will be a problem to update your code so it is better of putting your js files into dir but it does not mean that you can not run your javascript script code inline. Yes, you can do it as following.
<html>
<head></head>
<body>
<input type="text" id="myid">
<button id="mybtn">click</button>
<div id="mydiv"></div>
<script type="text/javascript">
var mybtn = document.getElementById("mybtn");
var mydiv = document.getElementById("mydiv");
var myid = document.getElementById("myid");
mybtn.onclick = function(){
console.log(myid.value);
mydiv.innerHTML = myid.value;
}
</script>
</body>
</html>
And since javascript code runs on the client-side. You can run it in your windows machine using a web browser and you do not need web-server. The purpose of pushing your js file or the whole project to the web-server is that your clients or people who visit your web site to use your online app in their local machines.

Related

External js file not working in mobile browser

Good afternoon/evening everyone
Why in mobile browsers (Chrome Mobile, Kiwi) the external js file is not visible in the html file ?
script.js :
alert('hello from script');
Next I try to include this file in html code with
<script src="script.js">
</script>
(both files are in the same folder)
This code only works on desktop, but doesn't work on mobile browser
I tried to determine the full path with :
output.innerText = location.href;
And then copied it to the src attribute :
<p id="output">
</p>
<script src="content://com.estrongs.files/storage/emulated/0/my_files/other/js/test%20script%20src/script.js">
//output.innerText = location.href;
</script>
Still doesn't work!
I've tried all kinds of ways: './sript.js' and type="text/javascript" also doesn't help
What else can be done ?
<script src="script.js"></script>
<p id="output"></p>
<script>
alert('hello from script');
</script>
Works fine...: https://jsfiddle.net/vm4y0h5L/
The "script" inclusion is just as simple as adding a "src line".
( https://www.w3schools.com/tags/att_script_src.asp )
For more info on alerts, see:
https://www.w3schools.com/jsref/met_win_alert.asp
PS:
Triple check your spelling ...
It's "script".
Thanks for the answer
I figured out what's up
I have installed Termux and local server NodeJS, wrote a simple script
var express = require('express');
var path = require('path');
var app = express();
var folder = '';
app.use('/', express.static(path.join(__dirname, folder)));
app.listen(8080, function ()
{
console.log("Server is running on port 8080.");
});
Now all tags with the attribute work correctly "src=..." (<script src="...">, <img src="...">, <link rel="stylesheet" href="...">)
All you have to do is type in the address bar of your browser:
localhost:8080/path to my .html

document.getElementById() is not defined when running browser code in VSCode

I was trying to use the document.getElementbyId() but when I run the console it tells me it is not defined.
My index.html and index.js are in the same folder the source should be OK.
I'm using Cmd + Shift + P in Visual Studio Code and then choose "Run: without debbuging". The error message shows in the integrated console.
let word1 = "Alex";
let word2 = "Toko";
let example = `${word1} ${word2}`;
var doc = document.getElementById("test").innerText = example;
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="test"> </p>
<script src="index.js"> </script>
</body>
</html>
The issue is the waqy you're running the code.
cmd+shift+P will run the index.js on it's own, and it won't know or care about the html.
Instead, open the html in your browser, and it should work.
The reason it won't work on vs code is that it runs the javascript file directly, and while the html links to the javascript, it won't work the other way around.
cmd+shift+P is used for server-side javascript, not client side. client side, you can just test in browser.

ng-include is not working

I have create a simple page using AngularJs. When I'm trying to include header.htm in index.html, nothing is appearing in browser.
index.html
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="">
<div ng-include="'views/header.htm'"></div>
</div>
</body>
</html>
header.htm
<h1>Header</h1>
You have not shown your folder structure and more over the definition of header.html.From next time try to create MCVE.
I created a fiddle to show how it works.
<div ng-controller="Ctrl">
<div ng-include ="'header.html'" onload='myFunction()'></div>
</div>
<!-- header.html -->
<script type="text/ng-template" id="header.html">
Content of Header html
</script>
function Ctrl($scope) {
$scope.myFunction = function() {
alert('header loaded');
}
}
Welcome aboard!
Please provide some logs so we know better about the situation. Also consider reading How to Ask.
You can show console errors in...
Chrome with
Alt+CMD+J on Mac OS, with (i suppose) Ctrl+Alt+J on Windows
Firefox with
Alt+CMD+K on Mac OS, with (i suppose) Ctrl+Alt+K on Windows
Now to my answer: You request views/header.htm so your file structure needs to look like this:
- index.html
- views
- header.htm
To test your site locally use a tool like http-server. Or when you are on a Mac or Unix based machine you can simply run python -m SimpleHTTPServer in your projects directory.
Hope that helped.

jQuery/ Javascript .get method for reading text files

I just started working on my school assignment with some regular expressions in Javascript. I can't seem to figure out how to actually read data from a text file into variable using jQuery method .get(). When I try my code out nothing happens. It seems like it never enters .get() section. Here is my code:
JS file:
document.getElementById('file').onchange = function(){
var file = "New Text Document.txt"; //this will later be the selected file
$.get(file,function(data){
var myVar = data;
$("#123").html(myVar);
});
};
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>animacija</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<script type="text/javascript" src="func.js"></script>
<div id="123"></div>
</body>
</html>
The code snippet seems to be ok, but it will not work locally since $.get is for ajax requests and requires full available server path.
I rather recommend you the use of FileReader API.
HTML
<title>animacija</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<input type="file" name="file" id="file">
<div id="123"></div>
</body>
JavaScript
document.getElementById('file').onchange = function() {
var file = this.files[0];
var FR = new FileReader();
FR.readAsText(file);
FR.onload = function(data) {
var myVar = data.target.result;
$("#123").html(myVar);
}
};
JSFiddle
Hope it works for you!
Most browsers will not allow file: resources to read other local files. This is to prevent attacks where a downloaded HTML document could start reading (and transmitting) the contents of your hard drive (or at least your Downloads folder) as soon as you open it.
The other thing you need to know here is that $.get is used for getting resources from an HTTP server, while file inputs are used to allow a user to select a file from their local drive. I realize in your case it's a little confusing, because your web page is on your local hard drive, but imagine if your HTML and scripts were being hosted online, and some other user (not you) was using them to process their own locally-stored files.
MDN has a good tutorial on how to get started with <input type="file"> inputs.
The code won't work locally due to cross-origin limitations.
It works fine when run on a remote server and all files are in the same folder.
If you want to read local files (aka. files selected by user through the file input) you can read more about FileAPI here:
https://www.html5rocks.com/en/tutorials/file/dndfiles/

How to run .exe file or .bat file based on button click event using Javascript

In my current project, I would like to run .bat or .exe file using button click event using JavaScript. The content of batch file is as shown below:
start "S:\" TemperatureSensor.exe
which start TemperatureSensor.exe file when TemperatureSensor button is clicked.
Code for HTML page is shown below:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="window.open('file:///S:/Test.bat')">Temperature Sensor</button>
</body>
</html>
When I clicked on Temperature Sensor button, it should run Test.bat file but it just display following in new page:
Am I missing ?? Is it possible to run .exe file using button click event??
Updated:
Code for HTML page is shown below:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="myFunction()">Temperature Sensor</button>
<script>
function myFunction() {
var oShell = new ActiveXObject("Shell.Application");
var commandtoRun = "C:\\TemperatureSensor.exe";
if (inputparms != "") {
var commandParms = document.Form1.filename.value;
}
// Invoke the execute method.
oShell.ShellExecute(commandtoRun, commandParms, "", "open", "1");
}
</script>
</body>
</html>
When I clicked on Temperature Sensor button it displays error: Uncaught ReferenceError: ActiveXObject is not defined.
Just save this code as RunExe.hta and not RunExe.html and executes it by double click on it !
EDIT : REMARK about (HTA) (HTML Application)
HTML Application (HTA) is a Microsoft Windows program whose source code consists of HTML, Dynamic HTML, and one or more scripting languages supported by Internet Explorer, such as VBScript or JScript.
The HTML is used to generate the user interface, and the scripting language is used for the program logic.
A HTA executes without the constraints of the internet browser security model; in fact, it executes as a "fully trusted" application.
further reading about HTA HTML Application
<html>
<head>
<title>Run Exe or Bat files from HTA by Hackoo</title>
<HTA:APPLICATION
APPLICATIONNAME="Run Exe or Bat files from HTA by Hackoo"
ID="MyHTMLapplication"
VERSION="1.0"/>
</head>
<script>
function RunExe(){
var shell = new ActiveXObject("WScript.Shell");
var path = '"S:/Test.bat"';
shell.run(path,1,false);
}
</script>
<input style="width: 170px; height:23px; color: white; background-color: #203040;
font-family:Book Antiqua;" type="button" Value="Temperature Sensor" onClick="RunExe();"
</html>
If you're using firefox you could use this addon to open batch or exe files.
Exe and batch files aren't opening in browser by default becaue of security restrictions.
In a later version of the addon there will be an enable preference for exe-files and these files will be disabled by default.
But at the moment you can create links like test and launch the file with a click.

Categories

Resources