How to get elements from another HTML file - javascript

I'm trying to make a node.js application that takes the input from a text box in an HTML file. I want to store this value in an array, although I'm not sure how. My overall goal is to make a chat application and I assume there is some easier way to get the input without having to reference an HTML file.
Also, are there any templates for an html file because I'm not very skilled enough with HTML to make a decent-looking webpage. So if there is some template I could use, everything would look better.
My code:
var events = require('events');
var express = require('express');
var http = require('http');
var app = express();
var msg = [];
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.read('/', function() {
});
app.listen(3000, function() {
console.log("Server is running on port " + 3000);
});
#firstHead {
font-family: Georgia, 'Times New Roman', Times, serif;
}
<header>
<h1 id='firstHead'>
This is a header!
</h1>
</header>
<body>
<input type="text" id="inText" placeholder="Enter text here" />
</body>
Help appreciated!

First of all, your HTML code has so many mistakes. This the correct version of your code (You won't be using it, it's just to give you an idea of what mistakes you've done):
<!DOCTYPE html>
<html>
<head>
<style>
#firstHead {
font-family: Georgia, 'Times New Roman', Times, serif;
}
</style>
</head>
<body>
<h1 id='firstHead'>
This is a header!
</h1>
<form id="msg" method="GET" action="/msg">
<input type="text" name="msgContent" id="inText" placeholder="Enter text here" />
<input type="submit" value="Send">
</form>
</body>
</html>
Now this HTML page will send input contents to localhost:3000/msg as a POST request See here for more details, the problem here is that page will be refreshed or redirected (depending on your implementation, you should in this case use AJAX if you want SPA). Even if you used AJAX it will be hard for you to implement a chat application using HTTP requests. It would be a better idea to use WebSocket protocol to achieve this functionality. There's a module called Socket.io that will help you a lot. It has an event-driven system as it's great for real-time applications, you can check their official website; they've have an example of a chat application written in few hundred lines of code.
Now let's move to your server-side code, firstly .. there's no method of express called read, here's a working version of your code:
var express = require('express');
var http = require('http');
var app = express();
var msg = [];
app.get('/', function(req, res){
//You should use some template engines like EJS or Pug to render your HTML page with messages or the user will see nothing
res.sendFile(__dirname + '/index.html');
});
app.get('/msg', function(){
msg.push(req.query.msgContent);
res.redirect("/");
});
app.listen(3000, function(){
console.log("Server is running on port " + 3000);
});
The above code will work as it should but you'll see nothing in the client-side cuz you didn't render (or send msg array to client-side script to embed it). I'm just trying to make things clear to you not give you an implementation of your idea
I hope this helped you a little.

Related

Node js server doesn't show images in html file

I'm trying to use node js to show an image within an html file, but the image doesn't show up.
If I try to open the html file with a browser the image shows up without problem, but when I run it from the node js server it doesn't work.
Here is my node js code:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('pruebaFoto.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Here is the html code:
<!DOCTYPE html>
<html>
<head>
<meta http-equi="refresh" content="1"> <!--I use this meta tag for refreshing the page each second-->
</head>
<body>
<h1>Image: </h1>
<img src="./image.jpg" alt="image">
</body>
</html>
The image and all the code are in the same path.
You need to create a router so the server can respond to different requests with different content.
There are many options for this, a popular option is to use a library like https://expressjs.com/

Replace text in textarea script + RTE

I have a javascript code that replace some words writen in text area. Eg. If I write word "dog" it will change it to word "cat".
<html>
<head>
<script>
function changeText(){
dt=document.getElementsByTagName("textarea")[0];
dt.value=dt.value.replace(/dog/g,"cat");
dt.value=dt.value.replace(/blue/g,"red");
dt.value=dt.value.replace(/good/g,"bad");
}
</script>
</head>
<body>
<textarea rows="10" cols="65"></textarea> <br>
<input type="button" value="change" onclick="changeText()">
</body>
</html>
I have two problems with this script and I don't know how to fix it.
How can I call external file with words for replacement? I will have 200+ words and it will better that I have them in separate file.
How to implement some simple RTE (eg. Nicedit) and still have working script? I try it and script doesn't work...
Thanks in advance for help! :)
Due to security reasons, your possibilites are limited. The best way to do it is to load txt/json/xml file from your server using AJAX technology. Keep in mind that it's an asynchronous method. Without JQuery (most popular JS library), with pure Javascript, you can achieve it with the code below:
var fileContent = '';
var client = new XMLHttpRequest(); // we create a request
client.open('GET', '/foo.txt'); // foo.txt is the name of the file
client.onreadystatechange = function() {
fileContent = client.responseText;
alert("Hooray! My file was loaded, this is its content: " + fileContent );
}
client.send(); // and we send a request
Every rich text editor has its own JS library and a way to get editor's content, so it really depends. For nicedit it's like this (assuming your textarea has an ID):
var nicInstance = nicEditors.findEditor('idOfYourTextarea');
var notes = nicInstance.getContent(); // voila - your content

Node.js post data that isn't a form

I have a folder icon, which when a user clicks on, I want to be able to find out what folder it in my node.js server.
HTML:
<header>
<script>
function newfile(filecode){
console.log(filecode)
$.post('/Y9computing', filecode).done()
}
</script>
</header>
<body>
<div class="folderIcon" onclick="newfile('Y9UNIT1')"></div>
</body>
node.js:
app.post('/Y9computing', function (req, res) {
console.log("FIRED!")
console.log(req.filecode) //don't know what to put in here
At the moment, the server logs "FIRED!" and then "undefined", I also think I'll have to respond from the server with something.

Node Server Not Loading CSS File

I'm making a chat application using a node server but when I start the node server and point my browser to localhost:3000 it loads the HTML document but not the CSS file which is supposed to load when the HTML document loads. How do you load the CSS file so that the HTML document uses it?
HTML document code
<html>
<head>
<title>Socket.IO Chat by Flow</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="chat.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="css.css">
<body>
<table align="center" id="chat-box">
<td>
<ul id="messages"></ul>
<form action="">
<input type="text" placeholder="Press enter to send a message..." autocomplete="off" id="m">
</form>
</td>
</table>
</body>
JavaScript document code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/chat.html');
});
io.on('connection', function(socket){
});
http.listen(port, function(){
console.log('Listening on port: ' + port);
});
You haven't defined any routes that would provide the CSS file. The only route you've defined is
app.get('/', function(req, res){
res.sendFile(__dirname + '/chat.html');
});
...which will only ever serve chat.html.
To serve other files/resources, define other routes, perhaps a catch-all route that serves any matching file from a public directory.
For instance, this tutorial says you can serve any static files from the directory public by doing this:
app.use(express.static('public'));
More about routing in the routing tutorial. That whole series of tutorials may well be useful, in fact.

Integrating Javascript Libraries with Google App Engine

Just starting to learn web programming (taking class CS 253 on Udacity).
My question is how does integrating JS and google app engine work? I know this is may be a fundamental question about web programming, but I really need some guidance on how to understand this concept.
I am trying to incorporate the Twitch Javascript API into Google App Engine. Basically, I would like to have a small website where users can login via Twitch and it stores their info into a database. I really do not understand how this is possible, since Twitch only has a Javascript API.
Here is the script that I have that works perfectly for connecting to Twitch (from the examples on their git page):
<html>
<head>
<meta charset="utf-8">
<title>TwitchTV SDK Example App</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ttv-api.s3.amazonaws.com/twitch.min.js"></script>
<script>
window.CLIENT_ID = '';
$(function() {
// Initialize. If we are already logged in, there is no
// need for the connect button
Twitch.init({clientId: CLIENT_ID}, function(error, status) {
if (status.authenticated) {
// we're logged in :)
$('.status input').val('Logged in! Allowed scope: ' + status.scope);
// Show the data for logged-in users
$('.authenticated').removeClass('hidden');
} else {
$('.status input').val('Not Logged in! Better connect with Twitch!');
// Show the twitch connect button
$('.authenticate').removeClass('hidden');
}
});
$('.twitch-connect').click(function() {
Twitch.login({
scope: ['user_read', 'channel_read']
});
})
$('#logout button').click(function() {
Twitch.logout();
// Reload page and reset url hash. You shouldn't
// need to do this.
window.location = window.location.pathname
})
$('#get-name button').click(function() {
Twitch.api({method: 'user'}, function(error, user) {
$('#get-name input').val(user.display_name);
});
})
$('#get-stream-key button').click(function() {
Twitch.api({method: 'channel'}, function(error, channel) {
$('#get-stream-key input').val(channel.stream_key);
});
})
});
</script>
<style type="text/css">
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>TwitchTV SDK Example App</h1>
<div class="status">
Status: <input readonly="readonly" size="60" val="Unknown"/>
</div>
<div class="authenticate hidden">
<img src="http://ttv-api.s3.amazonaws.com/assets/connect_dark.png" class="twitch-connect" href="#" />
</div>
<h2 class="authenticated hidden">Authenticated</h2>
<div class="authenticated hidden">
<div id="logout">
<button>Log Out</button>
</div>
<div id="get-name">
<button>Get TwitchTV Name</button>
<input readonly="readonly" size="50" value="Unknown"/>
</div>
<div id="get-stream-key">
<button>Get TwitchTV Stream Key</button>
<input readonly="readonly" size="50" value="Unknown"/>
</div>
</div>
</body>
</html>
How can I communicate data between this client side javascript and Google App Engine? Thanks!
Very broad question. But in general, regarding your case:
You should set up a receiving end (handler) on your App Engine application. It will handle the requests from your client side JavaScript (Hello, world example)
Second, you will need to actually send the data to the server. I see that you're using jQuery. In order to call the server we've seen in the Hello, world example, you'll write something like this: $.get('/', function(data) {console.log(data);}). This will call the server and print to the console the message you got from the server.

Categories

Resources