I have recently started working with JavaScript and Node and I'm having trouble working with the .ejs files.
I'm trying to implement a button in my page that gets a string inserted in a textarea and runs a function to evaluate if that string is a xml code (more precisely a Vast Tag, but that's not the point.)
So, I have something like this:
<div class="clear vastClass">
<h3> Vast Tag </h3>
<div class="vastClass" hidden>
<div>
<p>Please validate your code!</p>
<input type="button" id ="buttonVast" value="Validate">
</div>
<textarea id="vastTag" name="vastTag" class="form_creatives" value="">Insert you Vast Tag</textarea>
</div>
</div>
<script>
$("#buttonVast").click(function(){
// TODO
}
</script>
So here are a few questions:
I'm trying to use the node module xml2js to see check the text and I have read something online already (I don't know if they are right). e.g.:
The browser is running the .ejs file, so if I try to require('xml2js') it won't understand
I tried to use the browserify package, but I can't seen to make it work
I can only call a file.js using if that file is in my public assets folder. (indeed any file I try to access I get an 404 Page Not Found Exception)
So, my questions is if anyone have any tips on a method that works where I can either use the node module inside my script, OR If can define a function in a file.js and then call this function into the script, OR if anyone knows how browserify works and if it can be used to fix my problem.
To check if the string in a textarea is xml you can use a regex expression. This checks to see if the input starts with
Here's a working fiddle: http://fiddle.jshell.net/mikemjharris/j1nL8rz0/
The specific code to check for xml:
function checkXML () {
var textToCheck = $('textarea').val();
if( textToCheck.match(/\<\?xml /) ) {
alert('this is xml!');
} else {
alert('not xml');
}
}
Thanks for the reply #mikemjharris, but it doesnt really solve my problem.
After a couple more days searching, I've found out how to use browserify, so I'll answer it myself.
First, I had to create a .js file, let's say, main.js, where I declared and defined all the functions I wanted to use, e.g.
Main.js:
var xml2js = require('xml2js')
validateVast = function(vast){
var parser = xml2js.Parser()
parser.parseString(vast, function(err, result){
if(result && !err){
console.log(result)
}
else{
console.log(err.toString())
}
})
}
Then, in the terminal I used the command below to add a Bundle file to my public resources folder:
browserify folder/main.js -o public/js/xml2jsBundle
Then, in my html file, I added the line
<script src="js/xml2jsBundle.js"</script>
And then was able to call my function in the body of the html like:
<body>
<script src="js/xml2jsBundle.js"</script>
<input type="button" value="Validate" class="bt_Add" onClick="validate()">
<textarea id="vastTag" name="vastTag" class="form_creatives" value=""></textarea>
<script type="text/javascript">
function validate(){
var vast = $("#vastTag").val()
validateVast(vast)
}
</script>
</body>
Well, I guess this is it.
Thanks for your help, bye
Related
I'm trying to create a chrome extension, with the main code being in python but I'm struggling. I've succeeded in sending information from the user inputted from the HTML side to the python script, but not the other way around. Here's what I have so far (or the code that seems to be the problem):
Python:
#app.route('/get_data', methods = ['POST'])
def get_data():
taken = request.get_data()
taken2 = taken.decode()
print(taken2)
strength = int(taken2) #this works, I use this later in the code
my_variable = 5 #just for example
return jsonify(my_variable), 200
background.js (javascript)
function myAction(input) {
console.log("input value is : " + input.value);
newish = input.value
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xxhttp.open("POST", "http://127.0.0.1:5000/get_data");
xxhttp.send(newish);
//so sending newish here works, this shows up on my python console (strength becomes this)
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
<script src="background.js" type="text/javascript">
</script>
</head>
<body>
<h1>A Thing!</h1>
<div style="padding: 20px 20px 20px 20px;">
<h3>Hello,</h3>
<p>User input please? : </p>
<input id="name_textbox" />
<button id="ok_btn" type="button">OK</button>
</div>
</body>
</html> stuff
What I'm aiming for is for the my_variable to be accepted into the javascript file somehow, and then the html being able to access and display the contents of my_variable. I've tried looking around, but nowhere seems to have the exact thing I'm looking for (send python variable to separate html file for chrome extension). I'm at a bit of a loss, any help would be greatly appreciated, thanks!
Better way of doing it
Since you want to send the variable from python to html by reading the file, this is better than using the FS module in javascript.
example index.html code:
<body>
<h1>Hello, {first_header:}!</h1>
<p>{p2:}, {p1:}</p>
</body>
python code for the above:
newFileCode = open("index.html", "r").read().format(first_header='goodbye',
p1='World',
p2='Hello')
open("index.html", "w").write(newFileCode)
output in the HTML file:
<body>
<h1>Hello, goodbye!</h1>
<p>Hello, World</p>
</body>
read more about file handling in python here
PREVIOUS ANSWER
You can parse the data using JSON. Although, you'll need a new Node.js module fs https://nodejs.org/api/fs.html.
Once you've installed that module, you have to maintain two JSONs, one being a JS variable and the other being an external .json file.
Use this code to write in external JSON files in javascript:
fs = require('fs');
var name = 'fileName.json';
var m = {"example": "HELLO"}
fs.writeFileSync(name, JSON.stringify(m));
Use this code to read an external JSON file in javascript:
JSON.parse(fs.readFileSync(name).toString())
To get/read the data from the external JSON file in python use this code:
import json
# Opening JSON file
f = open('fileName.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
You can edit the file from javascript and can read it in python using a while loop
I'm pretty new to coding, and I'm trying to complete Codecademy's Javascript course. I've learned a little bit about HTML/CSS and I'm almost done with JavaScript. I've researched people having similar problems, but those solutions typically involve JQuery, which I haven't learned.
Here is my HTML (index.html):
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
</body>
</html>
Here is the beginning of my JavaScript:
alert();
// Acquire character's name and check to make sure it's a string
var charName = prompt("NASA Receptionist: 'Welcome to Mission Control.
May I have your last name, please?'");
var nameCheck = function(charName) {
while (typeof charName === "number") {
charName = prompt("NASA Receptionist: 'Surely, your name is not
a number... Please, may I have your last name?'");
}
};
nameCheck(charName);
NOTE: index.html is in the same folder as main.js
When I open the index.html, nothing happens, not even the opening alert(). Am I missing something?
You have error in your script as you cannot make javascript statements in multiple lines without using escaping slash .
I was getting this error :
SyntaxError: unterminated string literal
var charName = prompt("NASA Receptionist: 'Welcome to Mission Control.
Here is the modified code :
alert();
// Acquire character's name and check to make sure it's a string
//The \r\n\ will format the string in prompt and make it appear in new line
var charName = prompt("NASA Receptionist: 'Welcome to Mission Control. \
\r\n\May I have your last name, please?'");
var nameCheck = function(charName) {
while (typeof charName === "number") {
charName = prompt("NASA Receptionist: 'Surely, your name is not \
\r\n\a number... Please, may I have your last name?'");
}
};
nameCheck(charName);
Check in browser source file whether main.js is loaded.
use alert("= loaded =") to check alert is called or not
If you are not even getting the syntax error, then I think you maybe referencing main.js incorrectly. Are you sure you have this in the same directory as index.html.
Also, each time I run it, the typeof method returns "string", no matter if I enter a number or not.
alert(typeof charName);
Good morning!
I have been working on a client side browser based app using JavaScript that (all of a sudden) needs the capability to save and load files locally.
The saved files are plain text (.txt) files.
I have managed to get JavaScript to read existing text files. However, I am unable to find reliable information on how to create and edit the contents of these files.
Based on what I see online, I am under the impression that you can't do this with JavaScript alone.
I found out from another source that the best way to do this is outsource the file writing/editing to a Java file and let Java do the work.
I found a code snippet and tweaked it around a bit, but it is not working and I seem to be at a loss:
JAVASCRIPT
<!Doctype html>
<html>
<OBJECT ID="Test" height=0 width=0
CLASSID="CLSID:18F79884-E141-49E4-AB97-99FF47F71C9E" CODEBASE="JavaApplication2/src/TestJava.java" VIEWASTEXT>
</OBJECT>
<script language="Javascript">
var Installed;
Installed = false;
try
{
if (Test==null)
Installed = false;
else
Installed = true;
}
catch (e)
{
Installed = false;
}
alert ("Installed :- " + Installed);
TestStr = Test.SendStr("Basil");
alert (TestStr);
</script>
</html>
JAVA
import javax.swing.*;
public class TestJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
public String SendStr(String lStr)
{
return lStr + "!!!";
}
}
If someone could point me in the right direction or even just explain why this isn't working, I would appreciate it.
I believe the sandbox issue prevents all browsers from performing any and all local file writing, without an enormous amount of working around the access restrictions. It is easier to write files remotely on the server than to write them locally to the client. This is true across all browsers.
So while it may be possible to perform the load function, you cannot perform the 'save' function on the local machine.
I want to make a JQuery routine that can write information (append) to a text file that either exists or does not exists. If the file does not exists than it should create the file and if it does it should either append or start writing new data to the file. I think append would be the best choice for a file logger. So it must append the data to the file.
I found this code on the internet and am trying to work it around so that I can use it on my page to write information to a simple text file.
Question: How can I make the following code log to a file for download?
Below is the new code and how I read the page that was listed in the comments on how a logger in Java script should work. The code is not working and I am not really certain as to why.
I am not really certain as to how the download works either but if I can just get the logger to work I will be happy for the time being.
Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
<script src="log4moz.js">
</head>
<script>
getLocalDirectory : function() {
let directoryService = Cc["#mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
// this is a reference to the profile dir (ProfD) now.
let localDir = directoryService.get("ProfD", Ci.nsIFile);
localDir.append("XULSchool");
if (!localDir.exists() || !localDir.isDirectory()) {
// read and write permissions to owner and group, read-only for others.
localDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0774);
}
return localDir;
}
let myFile = XULSchool.getLocalDirectory();
myFile.append("someFile.txt");
let formatter = new Log4Moz.BasicFormatter();
let root = Log4Moz.repository.rootLogger;
let logFile = this.getLocalDirectory(); // remember this?
let appender;
logFile.append("log.txt");
root.level = Log4Moz.Level["All"];
appender = new Log4Moz.RotatingFileAppender(logFile, formatter);
appender.level = Log4Moz.Level["All"];
root.addAppender(appender);
this._logger = Log4Moz.repository.getLogger("XULSchool.SomeObject");
this._logger.level = Log4Moz.Level["All"];
this._logger.fatal("This is a fatal message.");
this._logger.error("This is an error message.");
this._logger.warn("This is a warning message.");
this._logger.info("This is an info message.");
this._logger.config("This is a config message.");
this._logger.debug("This is a debug message.");
this._logger.trace("This is a trace message.");
</script>
<body>
<form id="addnew">
<input type="text" class="A">
<input type="text" class="B">
<input type="submit" value="Add">
</form>
</body>
</html>
#Smeegs says this nicely
Imagine a world where any website can edit files on your computer
JavaScript (or jQuery) cannot touch the user's file system.
Even if you find some hacked up thing that works via ActiveXObject, you should not attempt to do this. Cross-browser support would be very narrow for this feature.
If you want to write out file, just provide the user with a download.
If this is just a means of reading/writing some kind of data, look into localstorage.
"wget http://www.example.com/file.doc" downloads that file to the local disk.
What is the equivalent of the above in javascript? for example, consider the following html snippet.
<html>
<head>
<script language="JavaScript">
function download_file() {
var url = "http://www.example.com/file.doc"
//
// Question:
//
// what should be done here to download
// the file in the url?
//
}
</script>
</head>
<body>
<input type="button" value="Download" onclick="download_file()">
</body>
</html>
Please suggest a solution that is compliant with all the browsers.
Sangeeth.
After a exploring more than a month, with a help of my friend, we were able to find out the following.
The website where the file is hosted is not allowing us to download the file using window.location = url; or window.open(url);
Finally we had to use the data-downloadurl support from HTML5 as follows
Click here to download the file
We embed this html into the host html and when clicked on the link, it triggers the download.
Why not use:
function download_file() {
var url = "http://www.example.com/file.doc"
window.location = url;
}
See https://developer.mozilla.org/en/DOM/window.location
If you need to open this in a new window/tab first then use:
function download_file() {
var url = "http://www.example.com/file.doc"
window.open(url);
}
See https://developer.mozilla.org/en/DOM/window.open
First thing that always comes in mind of every answerer to this question is executing wget shell command from java script.I'm almost certain that that's not possible because of
major security risk.
You pretty much need to have ajax which sends command to command line
either through php, or another scripting language via ajax...
You could probably make that happen with something like http://www.phantomjs.org/
I am saying probably because I read it from somewhere.