Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/263bbd7d94efad49a8ee4f68dbe4e09f to your computer and use it in GitHub Desktop.
Save code-boxx/263bbd7d94efad49a8ee4f68dbe4e09f to your computer and use it in GitHub Desktop.
PHP MYSQL AJAX Long Polling Example

PHP MYSQL AJAX LONG POLLING EXAMPLE

https://code-boxx.com/ajax-long-polling-php-mysql/

NOTES

  1. Create a database and import 1-score.sql.
  2. Change the database settings in 2-score.php to your own.
  3. Launch 3-score.html in your browser – Captain Obvious, AJAX calls will only work with http://, not file://.
  4. Insert a dummy score into the score table, and watch how AJAX long-polling updates the page.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `score` (
`time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`home` int(3) NOT NULL,
`away` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `score`
ADD PRIMARY KEY (`time`);
INSERT INTO `score` (`home`, `away`) VALUES
(12, 34);
<?php
class Score {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
protected $pdo = null;
protected $stmt = null;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE CONNECTION
function __destruct () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) GET LATEST SCORE
function getScore () {
$this->stmt = $this->pdo->prepare(
"SELECT *, UNIX_TIMESTAMP(`time`) AS `unix`
FROM `score` ORDER BY `time` DESC LIMIT 1"
);
$this->stmt->execute();
return $this->stmt->fetch();
}
}
// (D) DATABASE SETTINGS - CHANGE THESE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (E) CHECK FOR SCORE UPDATES
if (isset($_POST["last"])) {
// (E1) SET TIME LIMIT
set_time_limit(30); // set an appropriate time limit
ignore_user_abort(false); // stop when long polling breaks
// (E2) LOOP UNTIL THERE ARE UPDATES OR TIMEOUT
$_SCORE = new Score();
while (true) {
$score = $_SCORE->getScore();
if (isset($score["unix"]) && $score["unix"] > $_POST["last"]) {
echo json_encode($score);
break;
}
sleep(1); // short pause to not break server
}
}
/* (X) COSMETICS - DOES NOT MATTER */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
width: 100vw; height: 100vh;
padding: 0; margin: 0;
background: #000;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#sTime {
padding: 10px 0;
font-size: 20px;
}
#sTime, #sBoard {
width: 300px;
text-align: center;
color: #fff;
}
#sBoard {
display: grid;
grid-template-columns: 1fr 1fr;
}
#sHome, #sAway {
font-size: 60px;
padding: 20px 0;
}
#sHome, #sHomeT, #sAway, #sAwayT {
padding: 10px 0;
}
#sHome { background: #0b0558; }
#sHomeT { background: #221d64; }
#sAway { background: #580505; }
#sAwayT { background: #932828; }
<!DOCTYPE html>
<html>
<head>
<title>AJAX Long Polling Demo</title>
<meta charset="utf-8">
<link rel="stylesheet" href="3-score.css">
</head>
<body>
<!-- (A) HTML SCOREBOARD -->
<div id="sTime"></div>
<div id="sBoard">
<div id="sHome"></div>
<div id="sAway"></div>
<div id="sHomeT">Home</div>
<div id="sAwayT">Away</div>
</div>
<script>
// (B) LAST UPDATED TIMESTAMP
var last = 0;
// (C) AJAX LONG POLL
function poll () {
// (C1) FORM DATA
let data = new FormData();
data.append("last", last);
console.log("Fetch run", last);
// (C2) FETCH UPDATE ON SERVER RESPONSE
fetch("2-score.php", { method:"POST", body:data })
.then(res => res.json())
.then(data => {
// (C2-1) UPDATE HTML DISPLAY
document.getElementById("sTime").innerHTML = data.time;
document.getElementById("sHome").innerHTML = data.home;
document.getElementById("sAway").innerHTML = data.away;
// (C2-2) NEXT ROUND
last = data.unix;
poll();
})
// (C3) CATCH ERROR - LOOP ON TIMEOUT
.catch(err => poll());
}
// (D) GO!
window.onload = poll;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment