Implementing simple upvote downvote program - javascript

I am using express.js and jQuery to create a basic upvote downvote program. Basically the voting buttons increment/decrement by one whenever pressed and the result of each button click is displayed below. Nothing happens when the buttons are clicked, not even a Cannot POST /. I am not sure what is causing the error. This is what my main.js file looks like:
$(document).ready(function(){
$("#up").click(function(){
var up = $.post("/upvote", {changeBy: 1}, function(dataBack){
$("#upvote").text(dataBack);
});
});
$("#down").click(function(){
var down = $.post("/downvote", {changeBy: 1},
function(dataBack){
$("#downvote").text(dataBack);
});
});
});
and then on the server side server.js, I have this:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
var inc = 0;
var dec = 0;
app.post("/upvote", function(req, res){
res.setHeader("Content-Type", "application/json");
inc += parseFloat(req.body.changeBy);
res.write(JSON.stringify(inc));
res.end();
});
app.post("/downvote", function(req, res){
res.setHeader("Content-Type", "application/json");
dec -= parseFloat(req.body.changeBy);
res.write(JSON.stringify(dec));
res.end();
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
A bit of HTML:
<div class="buttons">
<button id="down">Downvote</button>
<p id="downvote"></p>
<button id="up">Upvote</button>
<p id="upvote"></p>
</div>

I used your code to create a jsfiddle and it seems to be working fine with click events. Of course the ajax calls error out but the click event handler itself seems to be called Chrome at least.
<div class="buttons">
<button id="down">Downvote</button>
<p id="downvote"></p>
<button id="up">Upvote</button>
<p id="upvote"></p>
</div>
$(document).ready(function(){
$("#up").click(function(){
var up = $.post("/upvote", {changeBy: 1}, function(dataBack){
$("#upvote").text(dataBack);
});
});
$("#down").click(function(){
var down = $.post("/downvote", {changeBy: 1},
function(dataBack){
$("#downvote").text(dataBack);
});
});
});
https://jsfiddle.net/j14qkyae/

i gave this a try and it works. Is this really the whole html you use? Then this is the error. You need to in include jquery and your main.js into the html. I copied a query.min.js into the public directory of the server.
<html>
<head>
<title>Up Down Vote</title>
<script src="jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<div class="buttons">
<button id="down">Downvote</button>
<p id="downvote"></p>
<button id="up">Upvote</button>
<p id="upvote"></p>
</div>
</body>
</html>

Related

No response after clicking button on JS

sorry for this very basic question.
So I want to know how to make buttons responsive.
I have a client.js and index.html as shown below
// Function to change the content of t2
function modifyText() {
const t2 = document.getElementById("t2");
if (t2.firstChild.nodeValue == "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
}
}
// Add event listener to table
const el = document.getElementById("myButton");
el.addEventListener("click", modifyText, false);
<table id="outside">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
<button id="myButton">Click Me!</button>
When I run on codepen it works fine.
But when I try to run these locally, with a server.js like this
console.log('Server-side code running');
const express = require('express');
const app = express();
// serve files from the public directory
app.use(express.static('public'));
// start the express web server listening on 8080
app.listen(8080, () => {
console.log('listening on 8080');
});
// serve the homepage
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
and I change the html into having a script calling the client.js
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Example-1</title>
</head>
<body>
<button id="myButton">Click me!</button>
<table id="outside">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
<script src="client.js"></script>
</table>
</body>
</html>
Then I run node server.js and I type localhost:8080 in my browser, the html file gets displayed but when I click the button, it doesn't cause any number changes.
How can I get these to work for real?
Also, ultimately I want the node.js server side to know a button has been pressed. Maybe print on the node.js console that "a button was pressed", whenever it was done on my browser. How can I achieve that?
What I want is to pass information from client side to server side easily but I am quite confused with how to do that and many people suggest different ways.
Edit:
Aligned file names.

Call an API-endpoint and print a message on client side by clicking a button

I have a very simple assignment for my school, but I just can't figure out how to solve it.
I need to create an endpoint for an API in Node.JS that responds to a GET request - so when I click the button in my HTML file, it should call my API endpoint and print the message "Hello World" and the number of times it has been called in an alert box.
UPDATED, UPDATED:
client/index.html
<html>
<head></head>
</body>
<!--
When clicking this button, an alert needs to show up
displaying a GET request from the server.js file with
the text "Hello World" a long with a number increasing
for each time, the call has been made
-->
<button id="myBtn" type="button" onclick="alertCount()">Send</button>
<script src="js/javascript.js"></script>
</body>
</html>
client/javascript.js
function alertCount() {
fetch("http://localhost:3000").then(res => {
console.log("log");
return res.text()
}).then(text => {
alert(text)
})
};
server/server.js
const express = require('express');
const app = express();
const port = 3000;
let counter = 0;
app.use(express.static('client'));
app.get('/', (req, res) => {
res.send('"Hello World!" has been called ' + counter + ' time(s).');
++counter;
});
app.listen(port, () => console.log("Listening..."));
You need to add a function in the onclick handler of the button. See an example here
// javascript.js
function myFunction() {
fetch("https://5f7203e364a3720016e61337.mockapi.io/text").then(res => {
return res.text()
}).then(text => {
alert(text)
})
}
<!-- index.html -->
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script src="javascript.js"></script>
EDIT: updated the script, all you need to do is replace the url inside the fetch()

Having internal server error in my nodejs code

i am currently having internal server error and i don't know why it occurs since i am a newbie in this field. Can anyone explain what is going on here and suggest me a possible way to fix my code ?.Oh, and off - topic a little, i don't know exactly what i have to do to be fluently in making a connection between nodejs server and ajax, can any one help me with that?. Please don't erase this. Thanks you a lot
Here is my nodejs server:
var express = require("express"),
bodyParser = require("body-parser"),
data = require("nedb");
var app = express(),
db = new data({filename:'infors'});
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/",function(req,res){
res.sendfile("html.html");
});
app.post("/login",function(req,res){
var user = req.body.user,
pass = req.body.pass;
db.insert({user:user,pass:pass});
res.end("login sucessful");
});
app.listen(3000);
Here is my html file:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var user,pass;
$("#button").click(function (){
user = $("#text").val();
pass = $("#text2").val();
$.post("http://localhost:3000/login",{user:user,pass:pass},function(data){
if(data == "done"){
alert("login success");
}
});
});
});
</script>
<fieldset>
<input type="text" id="text"/>
<input type="text" id="text2"/>
<input type="button" id="button" value="press here"/>
</fieldset>
</body>
</html>

NodeJS : How to have multiple methods for post

i am trying to make an iteractive form using nodejs.
Here is my web page
<!DOCTYPE html>
<html>
<script>
$('#ping-button').click(function() {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/process_test'
});
});
</script>
<body>
<form action="http://127.0.0.1:3000/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
<br>
<form action="http://127.0.0.1:3000/process_post" method="POST">
Team: <input type="text" name="team"> <br>
Player: <input type="text" name="player">
<input type="submit" value="Submit">
<br><br>
<button id='ping-button'>Ping</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</form>
</body>
</html>
and here is my app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('test'));
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.get('/process_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
app.post('/process_test', urlencodedParser, function (req, res) {
console.log("Ping");
res.end(JSON.stringify("Ping"));
})
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
team:req.body.team,
player:req.body.player
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
so i have two forms and a button. The first form is tied to the process_get method, the second form is tied to the process_post method and the button is tied to the process_test method.
both of the forms give expected results. When i click the button, it goes to the process_post method instead of the process_test
why does this happen?
The reason the Ping button submits the form to /process_post is because it is inside the form, and the click handler is not set due to errors.
If you open the console in your browser you will see Uncaught ReferenceError: $ is not defined. This is because you're using $ in your code, but you include jQuery much later in the page. This you can fix by loading jQuery prior to your script tag.
Once that is done you will notice that the button still does not work. This is because the script inside head is executed before the rest of the document is done, ie. the body contents is not there yet, and $('#ping_button') will find nothing. This you fix by wrapping you code inside $(document).ready(function() { // code here }); so it is executed once the whole page is loaded.
Still, clicking the button will send you to /process_post because the click event is not stopped in your click handler. Return false or use e.preventDefault() to disable the browser default action.
All this combined the head section (that was missing) will become
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#ping-button').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost:3000/process_test'
});
return false;
});
});
</script>
</head>
<body>
<!-- Rest of your page -->
</body>
</html>

Using Socket.IO and AngularJS to make Chat Application

I'm trying to make a chat application which I completed on Code School using NodeJS, Express, and Socket.IO. except where they used jQuery, I want to use AngularJS.
The problem that i'm having is that my $scope.model gets updated by an 'join' event emitted from my server, the client listens to this event and updates the $scope.model... but this change doesn't effect the DOM automatically like it's supposed to.
Index.html
<body ng-app="chatApp" ng-controller="ChatCtrl">
<header class="container">
<h1 class="page-header">Chatt App</h1>
</header>
<div class="container">
<div class="col-xs-3">
<ul class="list-unstyled">
<li ng-repeat="user in model.onlineUsers">{{user}}</li>
</ul>
</div>
<div class="col-xs-9">
<button class="btn btn-primary" ng-click="add()">Tester</button>
</div>
</div>
<!-- Vendors -->
<script src="vendors/jquery-1.11.3.min.js"></script>
<script src="vendors/angular.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<!-- app.js -->
<script>
angular.module('chatApp', [])
.controller('ChatCtrl', ['$scope', '$http', function($scope, $http) {
$scope.model = {
onlineUsers: ['test'],
};
var socket = io.connect();
socket.on('connect', function(data) {
var nickname = prompt("What's your name?");
socket.emit('join', nickname);
});
socket.on('join', function(onlineUsers) {
$scope.model.onlineUsers = onlineUsers;
console.log('model changed!');
});
$scope.add = function() {
var newUser = 'tester1';
$scope.model.onlineUsers.push(newUser);
};
}]);
</script>
</body>
Node.JS
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var onlineUsers = [];
// sets root
app.use(express.static(__dirname + '/public/src'));
io.on('connect', function(client) {
client.on('join', function(data) {
if(data === null) {
data = 'Nameless';
}
onlineUsers.push(data);
console.log(onlineUsers);
client.broadcast.emit('join', onlineUsers);
client.emit('join', onlineUsers);
});
});
server.listen(8080, function() {
console.log('Running at 8080');
});
I created a test button to add another item to the $scope.model.onlineUsers, and then finally, the DOM updates.
There is probably a better place to put my socket.io listening event's besides in my controller but I did also using a .run(function() {}); but this doesn't let me inject $scope for some reason, so i'm not sure where to put the code for the server in an Angular Project.

Categories

Resources