1<?php
2// (A) INIT
3session_start();
4$_SESSION['user'] = 1; // For this demo only, fixed to 1
5require "2a-reactions.php";
6$results = [];
7
8// (B) COMMON FUNCTION - GET REACTIONS
9function get () {
10 global $REACT;
11 global $results;
12 $results['react'] = $REACT->get([$_POST['id']]);
13 $results['user'] = $REACT->getUser([$_POST['id']], $_SESSION['user']);
14}
15
16// (C) HANDLE REQUEST
17switch ($_POST['req']) {
18 // (C1) SAVE REACTION
19 case "save":
20 $results['status'] = $REACT->save($_POST['id'], $_SESSION['user'], $_POST['react']) ? 1 : 0 ;
21 if ($results['status']) { get(); }
22 else { $results['error'] = $REACT->error; }
23 break;
24
25 // (C2) DELETE REACTION
26 case "del":
27 $results['status'] = $REACT->del($_POST['id'], $_SESSION['user']) ? 1 : 0 ;
28 if ($results['status']) { get(); }
29 else { $results['error'] = $REACT->error; }
30 break;
31}
32
33// (D) RESPOND
34/* $results = [
35 * "react" => REACTIONS FOR POST/VIDEO/PRODUCT
36 * "user" => USER REACTIONS
37 * "status" => 1 OR 0 (FOR SAVE + DELETE)
38 * "error" => ERROR MESSAGE, IF ANY
39 * ] */
40echo json_encode($results);
1<?php
2// (A) USER SESSION - FIXED USER ID TO 1 FOR THIS DEMO
3session_start();
4$_SESSION['user'] = 1;
5
6// (B) DUMMY POSTS
7$posts = [
8 "900" => "Foo Bar",
9 "901" => "Boo Bar",
10 "902" => "Goo Bar",
11 "903" => "Koo Bar"
12];
13$pid = [];
14foreach ($posts as $id=>$txt) { $pid[] = $id; }
15
16// (C) GET REACTIONS
17require "2a-reactions.php";
18$react = $REACT->get($pid);
19$ureact = $REACT->getUser($pid, $_SESSION['user']);
20
21// (D) OUTPUT HTML ?>
22<!-- (D1) CSS + JS -->
23<!-- https://cdnjs.com/libraries/font-awesome -->
24<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"/>
25<link rel="stylesheet" href="3b-posts.css"/>
26<script src="3c-posts.js"></script>
27
28<!-- (D2) POSTS LIST -->
29<div id="demo"><?php
30 foreach ($posts as $id=>$txt) {
31 $likes = isset($react[$id][1]) ? $react[$id][1] : 0 ;
32 $dislikes = isset($react[$id][0]) ? $react[$id][0] : 0 ;
33 $reuser = isset($ureact[$id]) ? $ureact[$id] : "" ; ?>
34 <div class="prow" data-react="<?=$reuser?>" id="prow<?=$id?>">
35 <div class="ptxt"><?=$txt?></div>
36 <div class="plike" onclick="react(<?=$id?>, 1)">
37 <i class="fa fa-thumbs-up"></i>
38 <span class="countlike"><?=$likes?></span>
39 </div>
40 <div class="pdislike" onclick="react(<?=$id?>, 0)">
41 <i class="fa fa-thumbs-down"></i>
42 <span class="countdislike"><?=$dislikes?></span>
43 </div>
44 </div>
45 <?php } ?>
46</div>
1#demo {
2 max-width: 600px;
3 margin: 0 auto;
4}
5.prow {
6 display: flex;
7 background: #fafafa;
8 border: 1px solid #ccc;
9 padding: 10px;
10 margin-bottom: 10px;
11}
12.ptxt { width: 100%; }
13.plike, .pdislike {
14 width: 80px;
15 cursor: pointer;
16 color: #bbb;
17}
18.prow[data-react="0"] .pdislike { color: #f12727; }
19.prow[data-react="1"] .plike { color: #0cb30c; }
20html, body { font-family: arial, sans-serif; }