I have to update the state of a div, the thing is like this. On 2 computers, the same web page must be open, and I have to be able to change the state of a div in one and automatically update it in the other without having to reload, I think that Ajax alone is not enough, since I do not want to put one kind of timer that reloads the div s automatically, if not, when clicking on a button on computer A, it will update on counter B Obviously using mysql and php. It's possible?
-
I think its must use interval ajax for display both computer Use server batch process to get data and write textfile(json) for client computer when Com A update div -> update data to database , Com B (interval script post ajax to get json obj in text file to append div tag by id )Peang Peang– Peang Peang2020-09-19 23:10:26 +00:00Commented Sep 19, 2020 at 23:10
-
1@PeangPeang but he don't want to use timersEyad Bereh– Eyad Bereh2020-09-19 23:27:09 +00:00Commented Sep 19, 2020 at 23:27
1 Answer
You're right, AJAX alone isn't enough.
What really serves your purpose is WebSockets.
In short:
The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.
Of course, understanding how WebSocket works is mandatory, but it would be a waste of time to use the interface directly and deal with it (unless for learning purposes), so i suggest using Puhser JS Library for this purpose.
Now, here's the flow of the steps:
- Get the free API keys of Pusher
- Include the client channels library
- Open a connection to channels
- Subscribe to a channel
- Listen for events
- Trigger events from your server
I want to focus on steps 5 and 6:
- You make an AJAX request from one page and this request is sent to the server, now instead of making the server responds directly you just trigger the responsible event for
<div>element update, that what needs to happen in step 6. - Since all the browsers are subscribed to the responsible event and are listening, when step 6 trigger this event all browsers recieves it , at this step 5 you would perform DOM manipulation to update the
<div>element.
I'm sorry if my explanation is bad, but don't worry because it's easier than it looks, the documentation explains it in an excellent way.