-
Notifications
You must be signed in to change notification settings - Fork 0
/
009:3 Heartbeat API.php
51 lines (45 loc) · 1.36 KB
/
009:3 Heartbeat API.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
# HEARTBEAT API
// allows near-real-time frontend updating
# SEND DATA
?>
<script>
jQuery( document ).on( 'heartbeat-send', function ( event, data ) {
// Add additional data to Heartbeat data.
data.myplugin_customfield = 'some_data';
});
// may sent TRUE value to indicate expecting data
</script>
<?php
# RECEIVE DATA
/**
* Receive Heartbeat data and respond.
*
* Processes data received via a Heartbeat request, and returns additional data to pass back to the front end.
*
* @param array $response Heartbeat response data to pass back to front end.
* @param array $data Data received from the front end (unslashed).
*
* @return array
*/
function myplugin_receive_heartbeat( array $response, array $data ) {
// If we didn't receive our data, don't send any back.
if ( empty( $data['myplugin_customfield'] ) ) {
return $response;
}
// Calculate our data and pass it back. For this example, we'll hash it.
$received_data = $data['myplugin_customfield'];
$response['myplugin_customfield_hashed'] = sha1( $received_data );
return $response;
}
# PROCESS RESPONSE
?>
<script>
jQuery( document ).on( 'heartbeat-tick', function ( event, data ) {
// Check for our data, and use it.
if ( ! data.myplugin_customfield_hashed ) {
return;
}
alert( 'The hash is ' + data.myplugin_customfield_hashed );
});
</script>