Jump to content

Need some help with long polling configuration


Flashmaster82
 Share

Recommended Posts

Ok i´m working on a auction site and i need to update some variables for the clients in real time without refreshing the page. So i looked around and found a script for this (long polling) and now i´m trying to implement this.

My page looks like this.

Overview.jpg

And my struction in the tree.

tree.jpg.0245e50c9a4d4b78ae8b6ee52845e532.jpg

 

This is my current script to update a table in the database. I have created an test table in the database just for testing purposes.

server.php, Location: root folder

<?php 
ini_set('display_errors', 1);
error_reporting(E_ALL);

class CustomerDetails {
  
  // (A) CONSTRUCTOR - CONNECT TO DATABASE
  protected $pdo = null;
  protected $stmt = null;
  function __construct () { try {
    $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
    ]);
  } catch (Exception $ex) { exit($ex->getMessage()); }}

  // (B) DESTRUCTOR - CLOSE CONNECTION
  function __destruct () {
    if ($this->stmt !== null) { $this->stmt = null; }
    if ($this->pdo !== null) { $this->pdo = null; }
  }

  // (C) GET LATEST DETAILS
  function getCusDetails() {
    $this->stmt = $this->pdo->prepare(
        "SELECT *, UNIX_TIMESTAMP(data) AS 'unix'
        FROM testtable ORDER BY 'data' DESC LIMIT 1"
    );
    $this->stmt->execute();
    return $this->stmt->fetch();
  }
}

// (D) DATABASE SETTINGS - CHANGE THESE TO YOUR OWN!
define("DB_HOST", "xxx");
define("DB_NAME", "xxx");
define("DB_CHARSET", "utf8");
define("DB_USER", "xxx");
define("DB_PASSWORD", "xxx");

// (E) CHECK FOR UPDATES
// ******** THIS IF STATEMENT IS NOT WORKING - WHEN REMOVED WE CAN PRINT_R THE CUSTOMER DETAILS AS ARRAY. WHEN USED THE IF STATEMENT RETURNS NO DATA. *********
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
  $_DETAILS = new CustomerDetails();
  //print_r($_DETAILS->getCusDetails());
  while (true) {
    $details = $_DETAILS->getCusDetails();
    if (isset($details["unix"]) && $details["unix"] > $_POST["last"]) {
      echo json_encode($details);
      break;
    }
    sleep(1); // short pause to not break server
  }

}

?>

 

Auction page

<?php 
ini_set('display_errors', 1);
error_reporting(E_ALL); ?>

 
<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("<?php echo $config->urls->httpRoot;?>server.php", { method:"POST", body:data })
  .then(res => res.json())
  .then(data => {
    //console.log(data);
    
    // (C2-1) UPDATE HTML DISPLAY
    document.getElementById("time").innerHTML = data.data;
    document.getElementById("id").innerHTML = data.pages_id;
 

    last = data.unix;
    poll();
  }) 
 
// (C3) CATCH ERROR - LOOP ON TIMEOUT
  .catch(err => poll());
}
 
// (D) GO!
window.onload = poll;

</script>
  
    
<div id="time">Time</div>
<div id="id">Id</div>    

 

But i don´t how to get the fields from the auction_page and auction_bid as in the first image to be updated. To get values from the database to this page/pages. Sorry for being such a beginner. But i´m in need for some guidance.

Or has somebody made a similair better code for this with ajax long polling into Processwire? Any help is highly appreciated.

Link to comment
Share on other sites

If you know what to do SSE is quite easy to implement and a great option. See https://processwire.com/talk/topic/26663-need-help-making-sse-work/

Though I wonder what that means from a performance / scalability point? What if we had 100 users viewing the website. With SSE that would mean 100 SSE streams. With polling that would mean 100 requests every X seconds.

Does anybody have an idea (or resources) what is easier for the server to handle? How can I test that? It's a blackbox for me at the moment 🙂 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...