WebSockets or AJAX — Modern PHP Development

Joshua Etim
4 min readOct 5, 2020

--

This article walks us through the advances in dynamic web development, and how we can improve the dynamic nature of our web apps.

So, before now, the web was just a bunch of static HTML pages. Send a request for a page, wait, get the content of the page — content already hand-typed by the web developer. Good old days.

It wasn’t long after until the need for dynamic pages became obvious (I wonder why 🙃 ), and developers sought a way to dynamically control the final content rendered to the client (which is the web browser).

I won’t bore you with tech history here, but you can deduce the timeline of events leading to the evolved server scripting languages we have now. Browsers could now send requests, with specific query parameters, which will be received by the server, performing the specified request, and generating content unique to that query.

That wasn’t enough, though. There was a need to take dynamism one step further: updating content of an already loaded web page. The best way of achieving that would be to figure out how to establish a persistent connection between the web browser and the server, allowing for an exchange of data through a well-defined protocol (for example, HTTP).

Want to read this story later? Save it in Journal.

Microsoft came through with the introduction of XMLHttpRequest, which will form the underlying foundation of AJAX (Asynchronous Javascript And XML), leading us into an era of client-side requests, without the need for reloading (asynchronous requests). The name XMLHttpRequest is a bit misleading now, because, HTTP is just one of the different protocols than can be used, and data can be retrieved via different forms like text, HTML, or JSON, not just XML.

The baseline for the XMLHttpRequest object as well as newer, more efficient techniques (such as the Promise-based Fetch API) is the consumption of REST APIs (Representational State Transfer APIs), which at its best, was a unilateral, CRUD-based, stateless protocol. (Unilateral — you could only send requests to the server, and get a response; CRUD-based — you could mostly perform the Create-Retrieve-Update-Delete functions; Stateless protocol — the client doesn’t need to know what is currently happening server-side, and vice versa — servers traditionally ‘remember the client’s data’ via cookies).

This conventional REST API — Stateless protocol is perfect — as long as your application doesn't require a constant exchange of server-client data. If it does, it’s bad.

Example of apps with constant server-client data exchange:
— Notification systems
— Real Time Charts (Statistics, Currency & Stocks patterns)
— Maps and Location Trackers
— Chatting / Messaging systems
— Live Video Streaming

And that’s where WebSockets come in.

I’ll try my best to explain WebSockets as simple as I can.

When a high-level protocol request is made asynchronously (such as CRUD), a connection is established between the server and the client, and that connection is short-lived. It exists only for that request, and once it’s completed (a status code returned, could be 200, 403, 201 — anything), the connection is ended. This means that if you wanted a notification system, you would keep sending requests asynchronously, probably with the Javascript’s setInterval() method, hoping that there will be a response, which will serve as a notification to the end-user. There are a lot of reasons why such practice is inefficient, but we will stick with the high-latency characteristic of such a method. This characteristic shows in delay in retrieving information, which could stack up over time, and probably results in large chunks of time-lapse. For reference, gamers call this phenomenon, lag.

With WebSockets, you have low-latency (fast) operations, with most of the issues of the REST-based request solved. You can check out the full difference between the REST API request and WebSockets requests here.

WebSockets create a long-lasting server-client connection, based on TCP (Transmission Control Protocol), and is indeed bilateral, stateful, and faster. This makes it a highly efficient alternative to the traditional HTTP asynchronous requests we are usually comfortable with. It’s your best bet for building real-time systems.

PHP and WebSockets

PHP doesn’t have native support for WebSockets. WebSockets was built to work in persistent connections, which is something most PHP servers don’t have. As expected, there are many ways around this.

Some third-party packages can be of help in interacting with WebSockets. One notable example is Pusher. There’s also Ratchet. These tools can help you establish persistent connections to facilitate server-client data exchange, and make modern dynamic development an easy job in PHP.

As mentioned earlier, this is not a tutorial on how to implement the WebSocket API in PHP. Due to (current) lack of native support in PHP, you will need to learn specific methods from the different package providers.

I’ll drop a few links below for free tutorials on implementing the service using specific packages. Maybe later, I’ll come up with a direct tutorial of my own.

Ratchet — https://www.twilio.com/blog/create-php-websocket-server-build-real-time-even-driven-application

Pusher (Laravel) — https://pusher.com/tutorials/web-notifications-laravel-pusher-channels

Conclusion

Now, you’ve come to understand how data is often exchanged persistently in modern web applications, and how traditional AJAX requests might not make the cut for consistent exchange requirements. Next time, when building a web application with PHP, take note of the data exchange process, and decide which connection is best to implement.

More from Journal

There are many Black creators doing incredible work in Tech. This collection of resources shines a light on some of us:

--

--