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.
Related
I am learning data science but I am still new to flask, html and Js.
I have developed a ML model for home price prediction and would love to deploy it to Heroku.
The problem is the drop down menu in my frontend is not updated by the locations I have passed in my python flask backend.
here are the important parts of my code.
server.py:
from flask import Flask, request, jsonify, render_template
app = Flask(__name__)
#app.route('/locations')
def locations():
response = jsonify({
'locations': get_location_names()
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
app.js
function onPageLoad() {
console.log( "document loaded" );
$.get("{{ url_for('locations') }}",
function(data, status) {
console.log("got response for locations request");
if(data) {
var locations = data.locations;
var uiLocations = document.getElementById("uiLocations");
$('#uiLocations').empty();
for(var i in locations) {
var opt = new Option(locations[i]);
$('#uiLocations').append(opt);
}
}
});
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Banglore Home Price Prediction</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"
type="text/javascript"></script>
<link rel="stylesheet" type= "text/css" href="{{url_for('static', filename = 'app.css')}}">
<script type="text/javascript" src ="{{url_for('static', filename = 'app.js')}}"></script>
</head>
the browser consoles prints "document loaded" which I placed in app.js but doesn't get the data from server.py.
I believe the issue is with the url_for statement but don't know how to go about it.
You can't use jinja2 expressions in a js file which is loaded as a static asset. - v25
You can add your Javascript in a <script> tag in the index.html file. Or you can hard code it.
I usually do not use either approachs. Instead, I render all the files with a custom python script before running the main app. I use a .bat file and type all the commands needed. You sometimes use Sass or any other thing that requires rendering... So it's helpful to be organized and write such a script. Use this approach if your JavaScript data doesn't change dynamically.
But if your script is dynamic, you can add a route that renders your file every time it is requested.
#app.route('/my_script.js')
def script():
return render_template('my_script.js', name='mark')
And in your /locations route:
<script src="{{url_for('script')}}"></script>
Jinja2 can parse any file regardless of it's type.
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 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
Using Python 3 with Socket.
I'm having trouble linking a javascript file to an HTML file. I have the following 3 files in particular in the same directory:
webserver.py
import socket
def getTextFromFile(filename):
with open(filename, 'r') as myFile:
return myFile.read()
host, port = '192.168.0.7', 11010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
print('Now serving: ' + host + ' at: ' + str(port))
while True:
try:
c, addr = s.accept()
print('Received connection form: ' + str(addr))
request = c.recv(1024)
response = '\HTTP/1.1 200 OK' + getTextFromFile("index.html")
c.sendall(response.encode())
c.close()
except Exception as e:
print(e)
index.html
<html>
<head>
<title>Title</title>
<script src="indexjs.js"></script>
</head>
<body>
<h1>Hello there.</h1>
<p>This is a webserver test.</p>
<button type="button" onclick="myFunction()">Click me!</button>
<p id="demo"></p>
</body>
</html>
indexjs.js
function myFunction(){
document.getElementById("demo").innerHTML = "Hello";
}
The web server code itself works fine, the router is port-forwarded, can be accessed from an entirely different network, yada-yada; but when the website is visited, the javascript doesn't seem to execute. If I place the same javascript code inside the script tags of index.html and omit indexjs.js then it does work as intended. How do I make it to where indexjs.js can be properly linked with index.html without putting the javascript code in script tags?
I also tried another similar approach by trying to put an image in index.html (png file, same directory as index.html of course) with the img tags, but it did not display either, so it seems like my code is having issues linking any files to index.html whatsoever.
The steps I'm taking:
Run webserver.py
Open browser (in my case it happens to be Chrome)
Type in my public ip xxx.xxx.xxx.xxx:11010 in the address bar, hit enter
The web page shows, but pictures don't show (or any other asset that's linked) and javascript functions aren't executed when, for example, buttons are pressed.
Any help would be appreciated, thanks in advance.
Normally you would have a public folder for your static assets. And you would put your static css and js files into it.
I have MqttConnect.js file and mqttws31.js lib . I have to mqttws31.js all source code include my MqttConnect.js file, How it possible?.
when I copy everything from mqttws31.js and past mqttconnect.js file .that time this error occur:
ReferenceError: Messaging is not defined
if I try this way it is working fine :
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script src="http://www.hivemq.com/demos/websocket-client/js/mqttws31.js" type="text/javascript"></script>
<script src="MqttJS/MqttConnect.js"></script>
</head>
MqttConnect.js file code :
// Using the HiveMQ public Broker, with a random client Id
var client = new Messaging.Client("broker.mqttdashboard.com",8000, "myclientid_" + parseInt(Math.random() * 100, 10));
//Connect Options
var options = {
timeout: 60,
keepAliveInterval:450,
cleanSession:false,
//Gets Called if the connection has sucessfully been established
onSuccess: function () {
alert("Connected:");
},
//Gets Called if the connection could not be established
onFailure: function (message) {
alert("Connection failed -: " + message.errorMessage);
}
};
function Connect(){
try {
client.connect(options)
}
catch(err){
alert(err.message);
}
}
mqttws31.js code:
http://www.hivemq.com/demos/websocket-client/js/mqttws31.js
UPDATE
where I want use this , there have no html page
This may be due to a quirk of how JavaScript loads. You can find a good example of how it should be done in this answer.
The quick answer is to place the loading of both JavaScript files into the body of the HTML document hosting them, with the MQTT library above your script.
Do NOT just copy the library into your own file, that's very poor form and a copyright violation if you don't credit the library's source properly.
Copy content of mqttws31.js into MqttConnect.js at the top (not at the bottom) and then load MqttConnect.js file:
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script src="MqttJS/MqttConnect.js"></script>
</head>
I tried this myself, I am not getting any error. (window is undefined)
There is a dependency between the two files, that is, there is code in MqttConnect.js which needs the code in mqttws31.js in order to work properly. So I'm assuming you pasted the contents of mqttws31.js at the end of MqttConnect.js. Pasting the contents of mqttws31.js at the beginning of MqttConnect.js should fix this. Your MqttConnect.js should look like
// Contents of mqttws31.js ...
// Contents of MqttConnect.js ...