I set the socket.emit event after a successful comment. But the problem occurs when I bind the sockets.on event. It fires several times.
$(document).on('click', '#comment_button', function() { $.ajax({ // upon success success: function (response) { if (response) { socket.emit('postcomment'); socket.on('refresh', function () { console.log('refresh'); //This console.log('refresh') is coming multiple times. I mean its occurance increases with every successful ajax response. }); } }); });
Here is my server.js
socket.on('postcomment', function () { io.sockets.emit("refresh"); });
I checked that in my server.js function socket.on socket.on called only once. I'm not sure what the problem is with socket.on('refresh', function () {} in ajax. Any help would be great.
The PS socket connection is already done. No problem with that.
EDIT: I fixed the error. If someone reads this in the future. As Jason and Niranjan mentioned, the socket.on{} event linked itself to a successful response. To be simple: Each time a click handler is called, it attaches additional event listeners to the socket. Listeners attached to previous clicks remain active.
so I made the following changes to the previous code
$(document).on('click', '#comment_button', function() { $.ajax({ // upon success success: function (response) { if (response) { socket.emit('postcomment'); } }); }); socket.on('refresh', function () { console.log('refresh'); });
Happy coding.
source share