Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic page refresh JavaScript/PHP or 'Pusher.com'

I'm looking for a solution to be able to dynamically force a refresh on my web page to all my current viewers. It would be easiest if this was done through php however I'm open to suggestions.

I have done some research and have found a possible solution (pusher.com) however I'm not sure how to execute this. Here is my code below:

JavaScript on my web page added to document.ready jQuery':

var pusher = new Pusher('xxx');
var refreshChannel = pusher.subscribe('refreshing');
refreshChannel.bind('refresh-event', function() {
location.reload(true);
});

Here is my php code from their official documentation:

<?php
 require('Pusher.php');
 $options = array(
 'cluster' => 'eu',
 'encrypted' => true
 );
 $pusher = new Pusher(
'xxx',
'xxx',
'xxx',
 $options);

 $data['message'] = 'hello world';
 $pusher->trigger('refresh-event', 'refresh', $data);

?>

I understand how to send a message like shown above but I don't know how to enable the refresh code. Has anyone used this sdk before and knows how?

Alternatively

Would anyone know any libraries or solutions on how to accomplish this task? Again, all I'm looking to do is refresh my web page dynamically to all my current viewers as and when I need to do it.

like image 785
user6934446 Avatar asked Jun 29 '26 11:06

user6934446


1 Answers

You callback function which is the second parameter to refreshChannel.bind(...) will run whenever a 'refresh-event' is received on channel 'refreshing'. The $data in your PHP gets passed to that function as well so you can send information with the event.

Your code to do this is almost spot on but it looks like you are forgetting to set the cluster in your javascript, so aren't successfully connecting. If your app is on the 'eu' cluster you need to say so when you try to connect:

var pusher = new Pusher('xxx', {
  cluster: 'eu',
  encrypted: true
});

You should have been getting "Could not find app by key xxx. Perhaps you're connecting to the wrong cluster." errors in the javascript console when you try to load the page.

edit: also on closer inspection your channel name and event are the wrong way around in your trigger call. It's

 $pusher->trigger('channel-name', 'event', $data);

edit 2: also in your javascript you're calling the channel 'refreshing' and in your php you're calling it 'refresh'. These have to be the same.

like image 83
Callum Oakley Avatar answered Jul 02 '26 00:07

Callum Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!