DEV Community

safejourney-art
safejourney-art

Posted on

Comments on Ajax and WebSocket

Hi, everyone!
This post is for my previous post 'Two ways to post data without reloading'. The contents written there are very nice and/or curious. All the techniques are correct. However, I have overcome troubles and difficulties and have learned a lot of new knowledges since I have posted it. I introduce you some new ideas.

Let's start with WebSocket.
In the previous post, we used a dummy span to emit a message to a specific person. Namely, a message is emitted to everyone through the dummy span. But the span is not displayed with CSS 'display:none'. And then the message is copied to a specific person.

I noticed a more simple way. It is to use a global variable.

var message;
socket.on('message receive', (msg) => {
    message = msg;
});
Enter fullscreen mode Exit fullscreen mode

In this way, the variable msg is substituted for the variable message and the message is locally displayed.
The point is, in WebSocket, the examle above is Socket.io, all things written within the function of 'socket.on' are globally emitted. On the one hand, even if the message goes through inside 'socket.on', it is locally displayed if it goes outside that.
You can use this way for both the client- and the server- sides.

Next, I comment on the difference between Ajax and WebSocket.
One is, of course, Ajax is always locally posted and on the one hand, WebSocket is normally globally emitted.
This means that Ajax doesn't need to use the technique above on the server-side.
Actually, NOT 'doesn't need to use', BUT 'cannot use'. This is (one of )the difference(s) between Ajax and WebSocket!
Namely, if you sent a message "Hello" using Ajax POST, the code on the server-side

var message;
app.post('/ajaxpost' (req, res) => {
    message = req.body.message;
    console.log("A: " + message);
});
console.log("B: " + message);
Enter fullscreen mode Exit fullscreen mode

returns 'A: Hello' and 'B: undefined'.
Well, above is the example of Express.js.
So, Ajax is always locally. But if WebSocket, you can.

Safe Journey!

Top comments (0)