I'm working on an ajax long polling function with mysql and it doesn't really seem to work. My computer is overheating and the website crashes after some minutes. Also, the poll.php doesn't even receive the content from data.php, instead, poll.php shows {"type":"connect_error).
I have not done any long polling before.
I have 3 files:
data.php
<?php
session_start();
define ('DB_HOST', 'localhost');
define ('DB_USER', 'root');
define ('DB_PASSWORD', 'root');
define ('DB_NAME', 'story_creator');
function sqlSelect($query) {
// Create connection
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, $query);
// Check connection
if (mysqli_errno($conn)) {
echo "Failed: " . mysqli_error($conn);
}
$resultArray = array();
if ($result) {
while ($row = mysqli_fetch_array($result)) {
$resultArray[] = $row;
}
}
return $resultArray;
}
$news = sqlSelect("SELECT type FROM users_news_feed WHERE user_id = {$_SESSION['user_id']} AND date > 0;");
echo json_encode($news);
?>
poll.php
<?php
$filename = 'data.php';
$lastmodif = isset($_POST['timestamp'])? $_POST['timestamp']: 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$response['type'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
Javascript
<script>
var timestamp = null;
function waitForMsg(){
$.ajax({
type: "POST",
url: "functions/poll.php",
async: true,
cache: false,
timeout: 50000, /* Timeout in ms */
data: { 'timestamp': timestamp },
success: function(data){
// if(data == ''){
// Just console.log the data
console.log(data);
setInterval(
waitForMsg(), /* Try again after.. */
1000); /* milliseconds (15seconds) */
// }
},
complete: function(){
setInterval(waitForMsg(), 7000);
}
});
}
$(document).ready(function() {
waitForMsg();
});
</script>