Reputation: 45
I installed socket.io into my app. However, when I press the submit button on my form, the page always refreshes.
I've looked this issue up on Google and StackOverflow, tried several solutions (such as making sure my sockets code is within $(document).ready()... code etc.) but still no dice.
I can briefly see a console.log stating the values of the data I put in my inputs, so that part works.
This is my code:
www
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('Webtech2:server');
var http = require('http');
//models
var Comment = require("../models/comments");
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
//Sockets komen hier
var io = require("socket.io")(server);
io.on("connection", function(socket) {
socket.on("postComment", function(data) {
console.log("Socket.io: server received POST");
//log data naar console
console.log("Client data log:"+data);
//stuur 'data' naar iedereen
io.sockets.emit("update_comment", data);
Comment.save(data, function(err,res) {
console.log(res+" added to DB");
io.emit('update:', res);
});
});
});
//op connection doe dit:
io.on("connected", function(socket) {
Comment.find().exec(function(err, output) {
socket.emit('show_data', output);
console.log("Output: "+output);
});
})
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
public/javascripts/sockets_comments.js (custom name)
//jquery voor sockets -- socket.io documentation/
$(document).ready(function() {
console.log("socket init ok");
var socket = io();
var result = "";
//data ophalen en naar mongod
$("#commentSubmit").on("click", function(e) {
var commentAuthor = $("#commentName").val();
var commentBody = $("#commentBody").val();
var commentDate = new Date();
//log van form data
console.log("Data opgehaald met waarde: "+commentAuthor+" als author, "+commentBody+" als bodyText en "+commentDate+" als tijdstip.");
//naar mongo
result = {
"cmt_author": commentAuthor,
"cmt_body": commentBody,
"cmt_date": commentDate
}.save;
//socket connect naar localhost op 3000 en post
var socket = io.connect("http://localhost:3000");
socket.emit("postComment", result);
console.log("Verzonden: "+result);
//reset inputs na send
$("#commentForm").val("");
});
//render
socket.on("updateComment", function(data) {
///
console.log("Data: "+data);
});
//loop visual data
socket.on("showData", function(output) {
//loop
for(var comments = 0; comments < output.length; comments++)
{
////
}
});
});
Relevant Jade view file
extends layout
block content
header
div.wrapper
a(href='/')
img(src="", alt="Logo")
a.hvr-grow(href="/discussions") All threads
span(style="color: white;") -
a.hvr-grow(href="/discussions/create") Start a new thread
div.pageContainer
h1 #{discussion.title}
span(id="categoryMarker" class="markers" style="font-size: 1.25em;") "#{discussion.category}"
span
a.hvr-grow(href="/discussions" style="float: right; margin-right: 25px;") Back to all threads
h3 Started by #{discussion.author}
| -
span Created on #{discussion.date.toDateString()}
span(style="display: none;") - #{discussion.location}
br
br
div#bodyText
p #{discussion.body}
div#commentsSection.pageContainer
form(action="" name="inputComment" id="commentForm")
input(id="commentName", placeholder="Your name" name="commentName" required)
br
br
input(id="commentBody", placeholder="Your comment" name="commentBody" required)
br
br
button(class="hvr-grow" type="submit" id="commentSubmit" style="color: black;") Post comment
script(src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js")
script(src="http://localhost:3000/socket.io/socket.io.js")
script(src="/javascripts/sockets_comments.js")
Upvotes: 0
Views: 1017
Reputation: 23267
Just put e.preventDefault();
at the beginning of the click
handler:
$("#commentSubmit").on("click", function(e) {
e.preventDefault();
var commentAuthor = $("#commentName").val();
//...
});
By the way, you don't have to connect to socket.io server on each click. You should connect only once as you did it with var socket = io();
, so you may delete this line:
var socket = io.connect("http://localhost:3000");
Edit: As @lxe noticed, it would be actually better to listen submit
event of the form since it would allow you to intercept pressing Enter
key as well.
Upvotes: 3
Reputation: 7599
You should listen to $("#commentForm").on("submit")
instead of $("#commentSubmit").on("click")
:
$("#commentForm").on("submit", function(e) {
var commentAuthor = $("#commentName").val();
// ...
return false; // don't forget to cancel the event too
});
EDIT: Here's a generic jsFiddle demonstrating this:
You can either click the button, or hit Enter (which is the beauty of the submit
event).
Upvotes: 3