Page Refresh triggered by Server | Ajax? [duplicate] - javascript

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function()
{
$("#notificationLink").click(function()
{
$("#notificationContainer").fadeToggle(300);
$("#notification_count").fadeOut("slow");
return false;
});
//Document Click
$(document).click(function()
{
$("#notificationContainer").hide();
});
//Popup Click
$("#notificationContainer").click(function()
{
return false
});
});
</script>
<style>
body{background-color:#dedede;font-family:arial}
#nav{list-style:none;margin: 0px;
padding: 0px;}
#nav li {
float: left;
margin-right: 20px;
font-size: 14px;
font-weight:bold;
}
#nav li a{color:#333333;text-decoration:none}
#nav li a:hover{color:#006699;text-decoration:none}
#notification_li{position:relative}
#notificationContainer {
background-color: #fff;
border: 1px solid rgba(100, 100, 100, .4);
-webkit-box-shadow: 0 3px 8px rgba(0, 0, 0, .25);
overflow: visible;
position: absolute;
top: 30px;
margin-left: -170px;
width: 400px;
z-index: -1;
display: none;
}
#notificationsBody {
padding: 33px 0px 0px 0px !important;
min-height:300px;
}
#notification_count {
padding: 3px 7px 3px 7px;
background: #cc0000;
color: #ffffff;
font-weight: bold;
margin-left: 100px;
border-radius: 9px;
position: absolute;
margin-top: 0px;
font-size: 11px;
}
</style>
</head>
<body >
<div style="margin:0 auto;width:900px; margin-top: 30px;">
<ul id="nav">
<li id="notification_li">
<span id="notification_count">5</span>
Notifications
<div id="notificationContainer">
<div id="notificationTitle">Notifications</div>
<div id="notificationsBody" class="notifications">
</div>
</div>
</li>
</ul>
</div>
</body>
</html>
I am working on a page that has getting the notification from the server. I just create a button and a small div for showing notification number. I want to make that div was getting the notification from the server when the server push to that div.
How can I get the push notification from the server. I want the client side code for receiving notification from sever. I just using another system and node js is the server.
Thank you.

You can achieve it using node js. Following is a working code example.
Node js : index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get("/", function (req, res) {
res.sendFile("index.html", {root: __dirname});
});
io.on("connection", function (socket) {
socket.on("notify", function (notification_request) {
io.emit('notify', JSON.stringify(notification_request));
});
});
http.listen(3000, function () {
console.log('listenting on 3000');
});
your frontent index.html before </body>
<script>
var socket = io();
$('button').click(function () { //notify event triggered
socket.emit('notify', {notification-1: "message1", notification-2: "message2", notification-3: "message3"});
return false;
});
socket.on('notify', function (notification) {
var notifications = JSON.parse(notification); //process notication array
$('#notification-div').append(notifications); //display the notification here which is going to be reflected for all clients
});
</script>
Run your index.js file on terminal or CLI to activate server. And Don't forget to install following node modules
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

Use http request object on javascript and get the response from it then append it to your html. Or you can use jquery ajax also.

The Best practice for notification mechanism in Node js is to use socket.io. It's really simple & easy to handle & best for real time updation.
Check out this link : -
http://socket.io/

Related

Failed to resolve module specifier "socket.io-client". Relative references must start with either "/", "./", or "../"

I am creating a chat application using socket.io.
I stuck into a error.if i removing the requiring socket.io-client the rest of the code running .but when i requiring the socket.io the it shows error "Uncaught TypeError: Failed to resolve module specifier "socket.io". Relative references must start with either "/", "./", or "../"."
I tried too many thing still facing this error pls help!
I tried insted of import,
require socket.io-client.
and also import the socket.io-client.
// server side
const app = require('express')();
const server = require('http').createServer(app);
const io = require("socket.io")(server,{
cors: {
origin: ["https://example.com", "https://dev.example.com"],
allowedHeaders: ["my-custom-header"],
credentials: true
}
});
// app.get('/', (req, res) => {
// res.sendFile(__dirname + '/index.html');
// });
server.listen(3000, () => {
console.log('listening on *:3000...');
});
enter code here
io.on('connection',socket=>{
consol.log("connection to server",socket);
socket.on('new-user-joined',name=>{
users[socket.id] = name;
socket.broadcast.emit('user-joined',name);
});
socket.on('send',message=>{
socket.broadcast.emit('recive',{message:message,name:users[socket.id]})
});
})
//client side
import { io } from "socket.io-client";
const socket = io();
const form=document.getElementById('send-container');
const messageInput=document.getElementById('messageInp');
const messageContainer=document.querySelector(".container");
const name = prompt("Enter your name to join:");
const append=(message,position)=>{
const messageElement=document.createElement('div');
messageElement.innerText=message;
messageElement.classList.add('message');
messageElement.classList.add(position);
messageContainer.append(messageElement);
}
form.addEventListener('submit',(e)=>{
e.preventDefault();
const message=messageInput.value;
append(`you: ${message}`,'right')
socket.emit('send',message);
messageInput.value='';
})
socket.emit('new-user-joined', name);
socket.on('user-joined',name=>{
append(`${name} joined the chat`,'right')
})
socket.on('receiv',data=>{
append(`${data.name}:${data.message}`,'left')
})
.logo{
display:block;
margin:auto;
width: 50px;
height:50px;
border: 1px solid black;
border-radius:40px;
}
body{
height: 100vh;
background-image: linear-gradient(rgb(85, 57, 57) , rgb(60, 82, 110));
}
.container{
background-color:rgb(194, 160, 160);
max-width: 800px;
height:400px;
margin: 10px;
margin:auto;
overflow-y:auto;
}
.message{
background-color: gray;
padding: auto;
width: 24%;
padding: 10px;
margin: 17px 12px;
border: 2px solid black;
border-radius: 10px;
}
.left{
float:left;
clear:both
}
.right{
float: right;
clear:both
}
.btn{
cursor:pointer;
border:2px solid black;
border-radius:6px
}
#send-container{
text-align: center;
display: block;
margin:auto;
width: 90%;
}
#messageInp{
width:62.1%;
border:2px solid black;
border-radius: 6px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>pro-chat realdtime socakat ios</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<nav>
<img class="logo" src="chat.jpg" alt="">
</nav>
<div class="container">
<div class="message right">Aniket:kase ho bhai</div>
<div class="message left">Raju:thik hai bhai</div>
</div>
<div class="send">
<form action="#" id="send-container" >
<input type="text" name="messageInp" id="messageInp">
<button class="btn" type="submit">Send</button>
</form>
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="js/client.js" type="module"></script> //here it showing the error
</body>
</html>
To load the client library, use this code:
<script src="/socket.io/socket.io.js"></script>
… which you already have.
Don't import it: You already have it.
Don't require it: You aren't running the code on Node.js and you already have it.
<script src="https://cdn.socket.io/socket.io-3.0.1.min.js"></script>
Use this as your script file, paste it in the html file and don't import or require anything in the server side
Use this:
(type="/module")
Instead of:
(type="module")

I don't know how to code the path in the POST request for my simple login form app

I have a simple login form app in node.js. I am able to display the login form and enter login data but my POST request to capture the login data doesn't work, I get POST http://localhost:3000/client 404 (Not Found) error at the js console. I think I am coding the path wrong in the post request. My HTML code for the login form is in the client.html file and my js code is in the server.js file. I am providing both.
Here is my client.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" content="width=device-width, initial-scale=1">
<title>Havuzlu Site main page</title>
<style>
/* Use havuzlusite picture as full page background. */
html {
background-image: url("/havuzlusite-img.jpg");
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
background-size: cover;
}
h1 {
color: black;
text-align: center;
}
/* Set general style for the button class. */
.button {
border: none;
color: white;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
/* Create classes for main page buttons. */
.bldgnews-btn {background-color: aqua; margin-left: 39%;}
.bldgmngmt-btn {background-color: blue; margin: center;}
.login-btn {background-color: blueviolet; margin-right: 39%;}
/* The popup login form - hidden by default */
.login-form {
display: none;
position: fixed;
bottom: 0;
right: 15px;
border: 3px solid #f1f1f1;
z-index: 9;
max-width: 300px;
padding: 10px;
background-color: white;
}
/* Set styling for the input fields of the login-form. */
.login-form input[type=text], .login-form input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
background: #f1f1f1;
}
/* Set additional styling When the input fields get focus (when they are clicked). */
.login-form input[type=text]:focus, .login-form input[type=password]:focus {
background-color: #ddd;
outline: none;
}
/* Set styling for the login button. */
.login-form .login-btn {
background-color: #04AA6D;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
width: 100%;
margin-bottom:10px;
opacity: 0.8;
}
/* Add a red background color to the cancel button */
.login-form .cancel-btn {
background-color: red;
}
/* Add some hover effects to buttons */
.login-form .btn:hover, .open-button:hover {
opacity: 1;
}
</style>
</head>
<body>
<! Create main page. >
<h1>Havuzlu siteye hoş geldiniz</h1>
<button class="bldgnews-btn" type="submit">Site haberleri</button>
<button class="bldgmngmt-btn" type="submit">Site yönetimi</button>
<button class="login-btn" onclick="openLoginForm()">Aidat takibi</button>
<! Create login form. >
<form class="login-form" id="loginForm" action="http://localhost:3000/client"
method="POST">
<h1>Kullanıcı girişi</h1>
<label for="isim"><b>isim</b></label> >
<input type="text" placeholder="İlk ve soy isim giriniz" id="isim" name="isim"
required>
<label for="sifre"><b>şifre</b></label> >
<input type="password" placeholder="Şifre giriniz" id="sifre" name="sifre" required>
<button type="submit" class="login-btn">Giriş</button> >
<button type="button" class="cancel-btn" onclick="close-Form()"> Kapat</button>
</form>
<script>
function openLoginForm() {
document.getElementById("loginForm").style.display = "block";
}
function closeForm() {
document.getElementById("loginForm").style.display = "none";
}
</script>
<script>src="/server.js"</script>
</body>
</html>
Here is my server.js file:
//import express, { static, urlencoded } from "express";
const express = require('express'); // Import Express package
const app = express(); // Create an Express app variable so that we can use Express in
anywhere.
const router = express.Router();
// add router in express app
app.use("/",router);
//import path from "path";
const path = require('path');
// Import body-parser module to parse incoming requests
const bodyParser = require('body-parser');
//import cors from "cors";
const cors = require('cors');
const port = 3000; //Set port to 3000.
// Below, we use the modules that we imported.
app.use(express.json() ); // use Express module body-parser to parse JSON-encoded request
bodies
app.use(express.urlencoded({extended: true})); // use Express module body-parser to parse URL-
encoded request bodies
app.use(cors());
// Send the local image file to be used as app homepage background, to the client.
app.get('/havuzlusite-img.jpg', function(req, res) {
res.sendFile("D:/Behrans-files/Web-projects/havuzlusite/havuzlusite-img.jpg");
});
// Send html code for app homepage and login page, to the client.
app.get('/', function(req, res) {
res.sendFile("D:/Behrans-files/Web-projects/havuzlusite/client.html");
});
//Route for login. When the user clicks Login button, we will post the //request to server and
//get the response.
//router.post('/client', (req, res) => {
app.post('http://localhost:3000/client', (req, res) =>{
console.log(req.body);
console.log(req.body.sifre);
res.end("yes");
});
app.listen(port, () => {
console.log("server is running at http://127.0.0.1:", port);
});
app.post should only take the path, not the entire URL (just like you did with `app.get):
app.post('/client', (req, res) =>{
// Here^
console.log(req.body);
console.log(req.body.sifre);
res.end("yes");
});

How can I let an html page rendered by node.js call back to the node.js file? [duplicate]

This question already has answers here:
Link index.html client.js and server.js
(1 answer)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 2 years ago.
I am trying to create a registry system with node.js and HTML, the problem is that my html page is rendered by node.js, and when i want to call it back to the node.js file, it seems like it cannot find the js file.
Here is my js code:
const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'content-type': 'text/html' });
const html = fs.readFileSync('Index.html');
res.end(html);
}).listen(3000, () => {
console.log('running on 3000');
});
function insertdatabase() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
const { Connection, Request } = require("tedious");
// Create connection to database
const config = {
authentication: {
options: {
userName: "******", // update me
password: "**********" // update me
},
type: "default"
},
server: "*********************", // update me
options: {
database: "************", //update me
encrypt: true
}
};
const connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on("connect", err => {
if (err) {
console.error(err.message);
} else {
queryDatabase();
}
});
function queryDatabase() {
console.log("Reading rows from the Table...");
// Read all rows from table
const request = new Request(
`INSERT INTO [dbo].[dbo] (email, username, password)
VALUES ('${email}', '${username}', '${password}');
SELECT * FROM [dbo].[dbo] `,
(err, rowCount) => {
if (err) {
console.error(err.message);
} else {
console.log(`${rowCount} row(s) returned`);
}
}
);
request.on("row", columns => {
columns.forEach(column => {
console.log("%s\t%s", column.metadata.colName, column.value);
});
});
connection.execSql(request);
}
}
and here is my html code:
<html>
<head lang="en">
<meta charset="UTF-8">
<style>
body {
margin: 0;
padding: 0;
background: url() no-repeat;
background-size: cover;
font-family: sans-serif;
background-image: url(image/hbg.gif)
}
.topnav {
overflow: hidden;
background-color: whitesmoke;
}
.topnav a {
float: left;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: white;
color: black;
}
.topnav a.active {
background-color: black;
color: white;
}
.register-box {
width: 380px;
height: 480px;
position: relative;
margin: 6% auto;
background-color: whitesmoke;
padding: 5px;
}
.userinput-box {
width: 100%;
padding: 10px 0;
margin: 5px 0;
border-left: 0;
border-top: 0;
border-right: 0;
border-bottom: 1px;
outline: none;
background: transparent;
}
.userinput-group {
top: 180px;
position: absolute;
width: 280px;
}
.button {
background-color: #cbcbcb;
}
</style>
<script src="server.js"></script>
</head>
<body>
<div class="topnav">
<a class="active" href="../Subpages/account.html">Log in</a>
Home
News
Contact
About
Shopping Cart
Billing info
</div>
<div class="register-box">
<br /><br /><center><h1><b>Register Account</b></h1></center>
<form class="userinput-box">
<center>
<h3>Email: <input type="text" name="email" id="email" required></h3>
<br /><h3>Username: <input type="text" name="username" id="username" required></h3>
<br /><h3>Password: <input type="password" name="password" id="password" required></h3>
</center>
</form>
<center>
<input type="submit" class="button" onclick="insertdatabase()">
<br />
</center>
</div>
</body>
</html>
My guess is that maybe an html page rendered by js cannot find other files? This guess is based on when I add the css file to the project, it cannot be found either. Is there a way to fix this problem, or do I have to try another method?
Here is an example of what you're trying to do, but putting the function in a client-sided file and using id to listen on the buttons. You should really avoid just putting an import to the server-side script in a client-sided file as it will be public and that could cause huge security issues.
If you want to use functions that are in your server.js file, you can use this. It's a way to use form submission in your express application.
In addition, don't put your submit button outside your form.

How can I create a separate client.js file with socket.io?

How should the chat application example (described on https://socket.io/get-started/chat/) look if I wanted the client script that currently exists in the index.html file, to exist in a separate client.js file? Note: In this example tutorial, I'm at the part where I'm trying to get a user connected to appear when refreshing the web page, but this is not working correctly.
I've tried including <script src="client.js"></script> in the head section of my index.html file, and then
const io = require('socket.io-client');
var socket = io();
in my client.js file, but it does not work. When I run node server.js, the chat application design displays on the web page correctly, and I show the listening on *:3000 text in the terminal, but not the a user connected text which should appear when I refresh the web page.
My server.js, index.html, and client.js files are all in the top level of the directory, and are as follows:
server.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html'); // Based on some research, I feel that the problem might
// be here, where I'm sending just a file, not a directory?..
});
io.on('connection', (socket) => {
console.log('a user connected');
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chat Application</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
<script src="client.js"></script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
client.js
// I am also unsure if the following is correct...
const io = require('socket.io-client');
var socket = io();
This is an old question but still an issue with the socket.io example code. I was able to figure it out. The issue is that the file-system works differently when running whatever server (including localhost).
In short, to resolve this issue, in index.js (or what is called server.js in OP's question), replace:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
with
app.use(express.static(__dirname));
app.get('/', (req, res) => {
});
(of course feel free to fill the app.get function later if needed.

Using socket.io in node.js with express to display connection message when user logs in

I am trying to write a web chat client in socket.io, but first I need to get my server talking to the website on localhost.
I am getting the 'listening' message, but nothing happens when I open up localhost in a new tab to say that a user connected. Apache server is running, so is express, so is node.js.
Here is my index.js, which serves up my index.html:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');});
io.on('connection', function(socket){
console.log('a user connected');});
http.listen(3000, function(){
console.log('listening on *:3000');});
and here is my index.html:
<!DOCTYPE html PUBLIC>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Web chat practice</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
Here will be the web chat:
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.();
</script>
</body>
</html>
I could also use some general direction in the MEAN stack.
This line of code in index.html creates an error:
var socket = io.();
The code should be:
var socket = io();
This will connect to your Express server/socket.io (if the web page is being served by that Express server). That should generate the 'a user connected' message in your server console, but it won't do anything else because your web page doesn't do anything else with socket.io.
In addition, your server code looks suspect. I'd suggest you take the Express 4 example right from here: http://socket.io/docs/#using-with-the-express-framework.
I do not understand why you mention an Apache server as that is not typically part of an Express/socket.io implementation.

Categories

Resources