javascript - Ajax mysql long polling -
i'm working on ajax long polling function mysql , doesn't seem work. computer overheating , website crashes after minutes. also, poll.php doesn't receive content data.php, instead, poll.php shows {"type":"connect_error).
i have not done 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 users_news_feed user_id = {$_session['user_id']} , 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 == ''){ // console.log data console.log(data); setinterval( waitformsg(), /* try again after.. */ 1000); /* milliseconds (15seconds) */ // } }, complete: function(){ setinterval(waitformsg(), 7000); } }); } $(document).ready(function() { waitformsg(); }); </script>
Comments
Post a Comment