DEV Community

safejourney-art
safejourney-art

Posted on

2 3

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!

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay