I know it might seem like a dumb question but even with all the examples i have looked through i can not get it too work.
I have the following code in my Javascript file
server.js
// Google Maps Locaton
googleMapsClient.geocode({
address: city
}, function(err, response) {
if (!err) {
basicLocation = response.json.results[0].formatted_address;
console.log(basicLocation);
}
});
});
function getBasicLocation() { // Able to grab location from index.ejs file
return basicLocation;
}
in my HTML im trying to update text as the location changes. My html code looks like this
index.ejs
<script src="../server.js">
</script>
<h3>
<script> getBasicLocation() </script> Location
</h3>
The way my files are set up in the directory is like
- app
- views
- index.ejs
- server.js
How do i get the getBasicLocation() to talk to my index.ejs file so that it updates the text?
Below steps should work -
Import server.js - You are doing this
create HTML node where you want location
e.g div id="location"
create script tag with below content
let lc = getBasicLocation();
document.getElementById("location").innerHTML = lc;
JQuery can further simplify your node selection code
Related
I'm new to Web Development (including JavaScript and HTML) and have a few issues within my personal project that seem to have no clear fixes.
Overview
My project is taking input from a user on the website, and feeding it to my back-end to output a list of word completion suggestions.
For example, input => "bass", then the program would suggest "bassist", "bassa", "bassalia", "bassalian", "bassalan", etc. as possible completions for the pattern "bass" (these are words extracted from an English dictionary text file).
The backend - running on Node JS libraries
trie.js file:
/* code for the trie not fully shown */
var Deque = require("collections/deque"); // to be used somewhere
function add_word_to_trie(word) { ... }
function get_words_matching_pattern(pattern, number_to_get = DEFAULT_FETCH) { ... }
// read in words from English dictionary
var file = require('fs');
const DICTIONARY = 'somefile.txt';
function preprocess() {
file.readFileSync(DICTIONARY, 'utf-8')
.split('\n')
.forEach( (item) => {
add_word_to_trie(item.replace(/\r?\n|\r/g, ""));
});
}
preprocess();
module.exports = get_words_matching_trie;
The frontend
An HTML script that renders the visuals for the website, as well as getting input from the user and passing it onto the backend script for getting possible suggestions. It looks something like this:
index.html script:
<!DOCTYPE HTML>
<html>
<!-- code for formatting website and headers not shown -->
<body>
<script src = "./trie.js">
function get_predicted_text() {
const autofill_options = get_words_matching_pattern(input.value);
/* add the first suggestion we get from the autofill options to the user's input
arbitrary, because I couldn't get this to actually work. Actual version of
autofill would be more sophisticated. */
document.querySelector("input").value += autofill_options[0];
}
</script>
<input placeholder="Enter text..." oninput="get_predicted_text()">
<!-- I get a runtime error here saying that get_predicted_text is not defined -->
</body>
</html>
Errors I get
Firstly, I get the obvious error of 'require()' being undefined on the client-side. This, I fix using browserify.
Secondly, there is the issue of 'fs' not existing on the client-side, for being a node.js module. I have tried running the trie.js file using node and treating it with some server-side code:
function respond_to_user_input() {
fs.readFile('./index.html', null, (err, html) => {
if (err) throw err;
http.createServer( (request, response) => {
response.write(html);
response.end();
}).listen(PORT);
});
respond_to_user_input();
}
With this, I'm not exactly sure how to edit document elements, such as changing input.value in index.html, or calling the oninput event listener within the input field. Also, my CSS formatting script is not called if I invoke the HTML file through node trie.js command in terminal.
This leaves me with the question: is it even possible to run index.html directly (through Google Chrome) and have it use node JS modules when it calls the trie.js script? Can the server-side code I described above with the HTTP module, how can I fix the issues of invoking my external CSS script (which my HTML file sends an href to) and accessing document.querySelector("input") to edit my input field?
I'm developping a website using WordPress in which I need to include some data-vis made with javascript. I need to load a file containing data in my JS script. Both the script and the data are located in my theme's folder with the following hierarchy :
theme
--scripts
----my_script.js
--data
----my_data.csv
Say I use d3.js to load the data in my script, using the following code :
d3.csv("path/to/data/my_data.csv", function(error, data){
// Use the data
});
What should path/to/data be ? I'm very confused. Should it be relative to where the script is ? Or to where the page using the script is ? Relative to the server filesystem, or to the site's domain ?
Since I didn't get any answers yet, here's what I ended up doing.
In the page template in which the visualizations are to be displayed, I added the following code to the body :
<script>
var theme_URI = "<?php echo get_stylesheet_directory_uri(); ?>";
</script>
This uses a WordPress function to get the path to the current theme, so getting the correct path to my data files is now trivial :
d3.csv(theme_URI + "/data/my_data.csv", function(error, data){
// Use the data
});
While trying to create a rich text editor, I cannot seem to add the js script for the buttons and form. Right now, most of the functions are inlined in the jade pages, but that is quite unelegant.
I have a layout.jade file:
doctype html
html
head
body
header
section.content
block content
And the create.jade script, where I want the rich text editor:
extends ../layout
block content
script(type='text/javascript', src='./css/js/wiz.js')
form(method="post", action=post ? '/post/edit/' + post.id : '/post/create', onload="iFrameOn()")
ul
p
input#title(name="title", placeholder="Title", value=post ? post.title : '', autocomplete='off')
p
#wysiwyg_cp(style="padding:8px; width:700px")
input(type="button", onClick="iBold();", value="B")
input(type="button", onClick="richTextField.document.execCommand(\"underline\",false,null);", value="U")
p
textarea#blogPostBody(style="display:none", name="blogPostBody", placeholder="Blog post text", rows="20", cols="50")
iframe#richTextField(name="richTextField", contentEditable="true", onLoad="richTextField.document.designMode = 'On';")
if(post)
| #{post.body}
else
| 	
p
input(onClick="javascript:submit_form();", type="button", name="myBtn", value="Save")
The structure of the project looks like:
Proj
- css
-- js
--- wiz.js
- middleware
- node_modules
- public
- routes
- views
-- post
--- create.jade
-- layout.jade
-- home.jade
-- login.jade
- app.js
- package.json
When trying to open the create section of my blog, I get the following error message, as can be seen in the image below:
Uncaught SyntaxError: Unexpected token <
See chrome stack: http://i.stack.imgur.com/JyHs2.png
The wiz.js file looks like this:
function iFrameOn() { richTextField.document.designMode = 'On'; }
function iBold() { richTextField.document.execCommand("bold",false,null); }
function iUnderline(){ richTextField.document.execCommand("underline",false,null); }
function iItalic(){ richTextField.document.execCommand("italic",false,null); }
function iImage() {
var imgSrc = prompt("EnterImageLocation", '');
if(imgSrc!=null) {
richTextField.document.execCommand("insertimage",false,imgSrc);
}
}
function submit_form() {
var theForm = document.getElementById("myForm");
theForm.elements("myTextArea").value = window.frames['richTextField'].document.body.innerHTML;
theForm.submit();
}
I have also tried adding
app.set('view options', {locals:{scripts:['wiz.js']}});
and/or adding
app.use(express.static("./css/js"));
In the app.js file or in the middleware.
But these did not help. The problem seem to be in the "create.jade" script, when referencing the 'text/javascript' script, because the same error was obtained even when referencing a non-existant js file.
Could anyone have any idea what the problem could be?
[EDIT] SOLUTION that was implemented:
script
include ./../../css/js/wiz.js
The following snippet of code worked:
script
include ./../../css/js/wiz.js
Express's static middleware will by default mount the files to the root. So, if you include the middleware as above, the wiz.js file will be accessible at "/wiz.js" when your server's running -- this is the path you should put in the src attribute of your script tag in the jade file, not the local path (since local files are not accessible to the client unless they are served). If you want to change the mountpath (so, for example, that the file will be accessible on "/js/wiz.js", rather than the root), you can add it as a first argument, like below:
var localDirectoryPath = "./css/js";
// Or if you happened to want an absolute path
// (though it doesn't make a difference here):
// var localDirectoryPath = require("path").join(__dirname, "css", "js");
app.use("/js", express.static(localDirectoryPath));
The temporary solution that you've found (using Jade's include function) is merely loading the file's contents on the server (when Jade compiles the template) and inserting the code in between script tags on your page, which works but is certainly not ideal, since it will slow down the initial loading of your HTML, especially as the wiz.js file gets bigger.
And I won't even ask why your javascript directory is inside your css directory!
I am trying to display a variable inside my Thermostat.js file onto my webpage using index.html, the variable name I want to pass into the webpage is "roomTemp". I searched some up and this is what I've come up with but I get a reference error in my console "$ is not defined" within my javascript file at line 5 "$('#printHere').html(roomTemp);".
Thermostat.js
var http = require('http'); //need to http
var fs = require('fs'); //need to read static files
var roomTemp=20;
$('#printHere').html(roomTemp);
//this function is identical to the serve file function from the course web page
//it will read the contents of a file and serve them as the specified content type
//this is only used to serve the static index page
function serveStaticFile(res, path, contentType, responseCode){
if(!responseCode) responseCode = 200;
fs.readFile(__dirname + path, function(err, data){
if(err){
//for now use success code
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('500 INTERNAL FILE ERROR' + '\n');
}
else {
res.writeHead(responseCode , {'Content-Type': contentType});
res.end(data);
}
});
}
//this function is nearly identical to the routing examples from the course web page
http.createServer(function (request,response){
var path = request.url.replace(/\/?(?:\?.*)$/,'').toLowerCase();
switch(path){
//serve the static index page
case '/index.html':
serveStaticFile(response,
'/index.html',
'text/html');
break;
default:
serveStaticFile(response,
'/index.html',
'text/html');
break;
}
}).listen(3000, "127.0.0.1");
console.log('Server Running at http://127.0.0.1:3000 CNTL-C to quit');
function save() {
var desTemp;
desTemp = document.getElementById("desTemp").value;
roomTemp = desTemp;
}
Index.html
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<p>Current Temp: <span id="printHere"></span></p>
<form action="demo_form.asp">
Desired Room Temperature: <input type="number" id="desTemp" onchange="save()"><br>
</br>
<input type="submit" value="Set">
</form>
</body>
</html>
You are getting confused with javascript, node.js scripts & asp.
In your thermostat.js, it's clearly a node.js (server side) script. You can't mix your client-side script (jQuery) on node.js.
$('#printHere').html(roomTemp);
This line is trying to search through the DOM and get the html values, which can't be done on the server side
Index.html
<form action="demo_form.asp">
You are creating a html page that has a form that submits to demo_form.asp, which again is another server side technology (Active Server Pages), by Microsoft.
Lastly, $ is just a shorthand for jQuery, you need to understand your software stack properly before attempting any further.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="Thermostat.js"></script>
</head>
You have to include these lines in you <script src="Thermostat.js"></script> in your head for your javascript to work. Remember defining the correct path for the src="<....\Thermostat.js">
Until you do not include your JS it won't work and also jQuery JS has to be included before your JS.
I have Durandal SPA which uses url.config.js file among different views. Bunch of urls to services are stored there.
Code for clarity:
define([], function () {
var serviceBaseUrl = 'http://localhost/Service/api/';
var portalPortalUrl = 'http://localhost/Portal';
});
And whenever I need to deploy my app, or run it with different IIS settings, I need to manually change this urls in code.
What I want:
To store them in Web.config file so I can have different configuration for debug and release modes.
I am using MVC 5 Razor views only for rendering bundles and initial content, all client side logic placed in Durandal folder.
I have only found solutions using ASP.NET ConfigurationManager like so:
function ReadConfigurationSettings()
{
var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
alert(k);
}
Or, for Razor:
#System.Configuration.ConfigurationManager.AppSettings["myKey"]
It's cool, but not my way.
Maybe it's possible to auto generate my urls.config.js file based on Web.config keys?
Thank you in advance.
If needed, here is my project structure:
- App //Durandal SPA
- Controllers
- Views //Only render initial view
- Web.config
You can use JavaScriptResult
Sends JavaScript content to the response.
Code, Controller Action method
public JavaScriptResult Config()
{
var script = string.Format(#"var configServiceBaseUrl = {0};", ConfigurationManager.AppSettings["var1"]);
return JavaScript(script);
}
In the page header(I would load the file first), You can define:
<script type="text/javascript" src='#Url.Action("Config", "Controller")'></script>
Now configServiceBaseUrl is Global JavaScript variable which you can use anywhere.
So you can use configServiceBaseUrl in url.config.js like
define([], function () {
var serviceBaseUrl = configServiceBaseUrl;
});
Adding to satpal, for SPA application such as angular js
For SPA's, such as angular you can use below code in your index.html as
<script type="text/javascript" src='/Controller/config'></script>