Search code examples
javascriptphpwebsocketreal-timephpwebsocket

Is there an alternative to realtime data?


I'm a begginer with programming, so I was looking for a way to have real time data in a web page I'm working with, specifically real time notifications. I use PHP for server-side code and Javascript for the client.

I tried to use websockets but the problem with it is that the web is hosted with Hostinger, and it doesn't allow me to use a shell to run the websocket server, or at least not without upgrading the service, also tried to run the command with PHP's shell_exec() but it is also disabled.

My only alternative is use the 'wss://echo.websocket.org' server or some other online but is not what I really want.

Is there another alternative to do this?

Thanks in advance.


Solution

  • One option is to have your front-end call a back-end "notifications" endpoint every x seconds to check for notifications. It may not be real time, but you can get close.

    Your JS could look something like this:

    let getNotifications = (url, params) =>{
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", url);
        try {
            xmlHttp.send(params);
            console.log(xmlHttp.responseText);
            //handle notifications here
        }
        catch(err) {
            console.log(err);
        }
        finally {
            setTimeout(() => {getNotifications(url, params);}, 5000);
        }
    }
    
    getNotifications('/api/notifications', null);
    

    This makes a request to /api/notifications every 5 seconds (5000 ms)