When to use node.js and when to use ajax?

I had a website , which was coded entirely in php and basic jquery ajax . However after i learned about node.js/socket.io i recoded almost all of the real time stuff that involved ajax using nodejs and socket.io . I am a bit confused as to whether i did the right thing . So my question is when is ajax a more optimal solution than using node/socket ?

Firstly, you should learn about the difference between the two, the answer will become clear.

AJAX are used for simple asynchronous requests. They don't require setting up a Node server and are supported on nearly every browser. They are used when you need to retrieve a piece of information from the server. They do however have the overhead of being sent over HTTP and therefore they need to be a proper HTTP request/response (adds weight).

WebSockets (available in a Node.js/socket.io setup) are used when you access some data frequently or you need to have a live, persistent connection with the server. You can establish a socket connection and send packets from the server to the client. This is lightweight compared to an AJAX solution, however Websockets are not supported by older browsers, and you need to setup a server that will handle such requests.

Socket.IO in particular uses a collection of different techniques so that you can get better browser support: long polling, multipart streaming etc.. This allows you to have that "instant" feedback from the server, however it still in most cases uses HTTP as the protocol. It will however use WebSockets if they are available (i.e. supported by the browser).

Actually in some cases Node.js/Socket.io will use AJAX.

If you're not working on an online game or if you don't need to update the state of your application frequently, I would suggest using AJAX instead of a Node.js/socket.io setup.

Nodejs is great for applications where you need to keep a persistant connection open between the client and the server. Basically if you want to send realtime data (chat client, game, etc.) between the client and server nodejs is a great option.

With nodejs this kind of persistent connection won't block other requests. Many other langauges like php (where each connection starts a new server process) struggle in such situations and you will likely end up with huge CPU load.

Socket.io and node.js together is an even better option if realtime data with the lowest possible latency is the goal. It will only fall back to long-polling when other technologies aren't supported, its preference is to use web sockets.

Of course both apache (with php) and nodejs can do AJAX, the question should really be whether that's the right way for you to transfer data, we need to know more about what you're trying to achieve!