Is my implementation of websockets accurate?

Context:

  • I am currently utilizing the Pusher API.
  • PHP serverside functionality is being employed.
  • The Pusher package has been installed on the server side via composer.

Implementation Approach

I am in the process of creating a slideshow controlled by a single user. Whenever this user changes the slide, I trigger an AJAX call to update all users viewing the page with the new slide number.

$('#nextCard').click(function(){
    if ($('#card-' + (cardId + 1)).length != 0) {  
        $('#card-' + (cardId)).hide();          
        cardId++;                                 
        $('#card-' + (cardId)).show();            
        location.hash = cardId;

        /**
         * make ajax call to push function
         */
        $.ajax({
            method: 'post',
            url: '<?php echo base_url('learn/pusher'); ?>',
            data: {card_id: cardId},
            dataType: 'json',
            async: false,
        });
    }
});

The updated slide number is sent through AJAX to the server and then relayed to users via Pusher in real time.

Pusher distributes the slide number simultaneously to all users on the same page, facilitating the seamless distribution of changes across multiple screens.

var channel = pusher.subscribe('notifications');
channel.bind('new-notification', function(data) {

    // call appropriate function

});

After receiving the data pushed by Pusher, the corresponding function is executed to reflect the changes.

Inquiry

Initially, I presumed that Websockets was meant to replace technologies like AJAX. However, my current setup entails using AJAX to transmit Websockets data to Pusher from the server side.

I believed Websockets to be superior to AJAX due to its speed, but it seems that my reliance on AJAX may be hindering this aspect.

Am I employing Websockets correctly in this scenario?

Answer №1

Utilizing AJAX to send requests to your server, which then activates a Pusher event to distribute it to subscribers, is a common approach when working with Pusher. While the underlying WebSockets technology supports bidirectional communication (additional details here), Pusher's pub/sub model operates in a unidirectional manner.

An alternative solution for your scenario would be to utilize client events. This method enables you to directly trigger events from the client side. However, it is important to note that when employing this technique, you must use private or presence channels.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch up the text when the image link is being hovered over

Is there a way to change the text color of the "a" tag when it is not wrapping the img link? <li> <a href="# WHEN I HOVER THIS IMG LINK I WANT A TAG BELOW TO CHANGE COLOR"> <img alt="Franchise 16" src="#"></img> < ...

3D Object Anchored in Environment - Three.js

In my current scene, I have two objects at play. Utilizing the LeapTrackballControls library for camera movement creates a dynamic where one object appears to rotate based on hand movements. However, an issue arises as the second object also moves along w ...

Identifying Angular 2 templates post-file separation: a step-by-step guide

I am currently trying to figure out how to initiate a project in Angular 2 and have encountered an issue. Following the steps outlined in this Angular 2 guide, I was able to separate my .ts files from .js files by configuring my 'temp' directory ...

What is the reason for importing this JS module in TypeScript with a "default" property?

This particular code snippet comes from a specialized i18n module, situated within ./esm/locale/en.js: import cardinal from '../rules/rule5'; import ordinal from '../rules/rule42'; var pluralRule = { ordinal: ordinal, cardinal: card ...

Updating the values of parent components in Vue.js 3 has been discovered to not function properly with composite API

Here is a Vue component I have created using PrimeVue: <template lang="pug"> Dialog(:visible="dShow" :modal="true" :draggable="false" header="My Dialog" :style="{ width: '50vw' }" ...

Baffled by the intricacies of jQuery

As a newcomer to jQuery, I stumbled upon this code snippet and am curious about its function. It seems like it is replacing an element with the id reveal to a link with the class html5lightbox and id reveal. However, the part that puzzles me is $( '#r ...

Establishing the default value of an input field in Angular by referencing another field

Within an Angular (1.5) setting, I am confronted with a form containing two input sections: ID URL The requirements are as follows: If the ID section remains vacant, the URL field should likewise be left empty. If the URL area is entered manually, it ...

Perform an AJAX post in Laravel 5.6 without using a form

I am trying to implement Ajax with Selectize for dynamically loading database results when a selection is made. I specifically need to use the POST method as I have data that needs to be sent to a specific URL. The function I've created looks like th ...

Creating an array in Javascript and populating it with dynamically generated values

I am currently iterating through 3 arrays, searching for 'actionTimings' in each array and summing up the values of actionTimings (which are all numbers). How can I store these 3 values in a new array? This is what I have tried so far... $.each( ...

Can a props be retrieved and passed as an argument to a function?

My goal is to retrieve a prop from MapsStateToProps using react-redux's connect and then pass it to a child component. This prop serves as an argument for a function, which in turn returns something that becomes the state of the child component. Alth ...

In a peculiar occurrence, the behavior of array.splice is exhibiting unusual characteristics within an

Be sure to take a look at this plunkr for reference: http://plnkr.co/edit/FQ7m6HPGRrJ80bYpH8JB?p=preview I'm encountering an issue where, after adding an element and then deleting it from the array using the splice method, everything becomes disorg ...

Utilize NProgress alongside the "React.lazy" feature for optimal performance

Check out my component hierarchy: <BrowserRouter> <Suspense fallback={<h1>MyFallback</h1>}> <Switch> <Route component={HomePage} path="/" exact /> <Route component={lazy(() => import(&apo ...

Preserve the wpColorPicker selection using personalized knockout bindings

Utilizing wpColorPicker and knockout, my goal is to update the color picker value in my observable and then store it in the database as JSON. While other elements successfully update and save, there seems to be an issue with my custom binding for the data ...

Determine the sibling input value using jQuery in an ASP.NET MVC application

In my Asp.net MVC project in Visual Studio 2015, I have a page where I need to update the user's shopping cart with ajax when the quantity of an item is changed. The challenge I'm facing is retrieving the Article Code from another input field in ...

Experiencing difficulties in updating the Express page

Encountering an issue with page refreshes, I'm struggling to make it work smoothly. The process begins with filling out a form on an HTML page, which then posts to an API on a different service using the Node RequestJS module. After the post, the othe ...

Transform a nested JSON array into a JavaScript array

I have a JSON array that looks like this (shortened for simplicity): [ { "name": null, "code": null, "results": [ { "date": "2012-04-28T06:00:00.000Z", "name": null, "value": 135, "unit": "MG/DL", ...

The function .then is not compatible with AngularJS

I have a service that is responsible for loading data. angular.module('App').service('daysService', ['$http','$q',function($http,$q) { var days = []; return { loadDay: function() { ...

Exploring the implementation of async.each with request in the Node.js Express framework

I'm currently working on a node.js project where I need to send multiple API requests in an iterative manner, so I decided to use the async.each method for this purpose. However, I encountered an issue where the console reported that the 'url&ap ...

Using Firebase collection inside an Angular constant

Currently, I am working on a Datatable using ng-bootstrap that utilizes a static array to display data. There are 3 main files involved: In the "country.ts" file, the necessary values are declared: export interface Country { id: number; name: string; ...

utilizing asynchronous functions with socket.io for optimized performance

This particular code snippet initiates the first emit to the client, which is received as the messageStart: 'Job is starting...' This part is functioning correctly. Following that, the code launches puppeteer to take a screenshot named example.pn ...