在不同的浏览器中同时显示相同的内容

I am developing a numbers game where users will buy numbers and after 2 days winners will be drawn.

I am using PHP for the backend and jQuery for the frontend.

My problem is when drawing occurred user on different browser can't see same numbers, these draw numbers are being generated by PHP.

I was thinking maybe I can build these game by PHP and Javascript but it looks not easy. Can you guys please suggest some alternative? How can I improve this code to show the same number on the different browser?

I have the idea that it is not possible to generate a random number for each request. Maybe I can save the number in the database and then get this number in PHP such that the number will be unique for each request.

The actual issue is to create the same content for each user in different browsers. Any help would be really appreciated.

Javascript:

var myTimer = setInterval(checkDrawDate, 1000);

function checkDrawDate() {
      var today = new Date();
      var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
      var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
      var dateTime = date+' '+time;
      var x = new Date(dateTime);
      var y = new Date("{{$drawDate}}"); //this is laravel variable which contain drawdate e.g. 2017-07-05

      if(x >= y){
          drawNumber();
    }
}

function drawNumber(){
      $.get("{{ route('ajaxcomparepowerball') }}",{'gameId': gameid}, function(res){
       $('#mybets').html(res.html); 
     });
}

PHP:

public function ajaxDrawNumber(Request $req){
     return rand(0,49);
}

A Cron Job will be needed to implement this functionality. As you are drawing a number on particular time (after $drawDate in your case). So the cron job will execute once in day, check whether $drawDate for each game is today or passed. If condition true, $drawDate <= now, call a function to generate random draw number rand(0,49) and save it to database corresponding to gameid of matched games(having $drawDate <= now).

By doing this, a lot Javascript work will be reduced. In JS, then need to hit an ajax request with gameid to fetch record having draw number for particular game from database. If record not found, it means random number not drawn yet.

I think you are using Laravel, so to schedule tasks in laravel visit here.

Here some possible solutions.

  • If you need the same data modified for users in real time I think the best option is WebRTC, quick start here. And here a simple example sending strings in real time between clients. If you also need interaction server to client you could use server-sent events.
  • You could perform a bidirectional communication between browser and a server using WebSockets. You can send and receive event-driven responses. Using a database you could communicate two clients.
  • The easiest is using a database to store the information and perform ajax to send data to the server (and database) and server-sent events to send data to the clients.

Basic Server-sent event example:

Javacript:

    var evtSource = new EventSource("myserver.php");
    evtSource.onmessage = function(e) {
    // listening for new messages here   

   alert(e.data)//  e.data is mynumber

    } 

Php (myserver.php)

<?php    
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream

");       

while (1) {

  //perform a query in your database with your driver
  $result = mysql_query("SELECT mynumber FROM mytable WHERE user = 1");
  $row = mysql_fetch_assoc($result);

    echo $row['mynumber'];//<-- sending mynumber to client    

  ob_end_flush();
  flush();
  sleep(1);// <-- this is every second, but you could fire this with ajax or some other event.

}

This code send a number from server to a client that is listening. If a user made a change, one possibility is that client send an ajax to update some value in the database. So, at the same time, the ajax server could send this as an update to clients listening. In that way the whole process is completed.

I think all you need is this. Call a function in every, say 5 seconds or less and fetch data from server and update it in the page.

window.setInterval(function(){
  updateNumber();
}, 5000);// set for every five seconds

 function updateNumber(){
//ajax code to fetch live data and append the data in the numbers container
}

And dont forget to cross check the data before saving the numbers in the server.

Hope it helps.!!!

To save and maintain users state, key value store like Aerospike can be used. It is very easy to save and retrieve data in key value store. In above case we just have to generate a unique key using gameId, userId and date. And save user's data against the unique key.

To get started with Aerospike php client following is Aerospike php client

If data is present against the unique id for that particular user just return it, else create the new random number save it against the unique key and return it. Please be careful while creating unique key. Instead of using server side date-time please send date in ajax call request so there will not be any issue with time zone. It will be always user's timezone and there will not be any issue if server is in different timezone and user is in different timezone.

function drawNumber(){
  $.get("{{ route('ajaxcomparepowerball') }}",{'gameId': gameid,'date':user-timezone-date}, function(res){
   $('#mybets').html(res.html); 
 });
}

Here "user-timezone-date" should be fix date format like 'MM-dd-yy' which will indicate the same day. hours or seconds should not be included while generating unique key otherwise at the time of retrieving the user's state; generating particular unique will be changed every hour or every second and whole purpose of of doing this will be shattered.

I am new to StackOverFlow so I am not able to comment on the answers. In case of corn job as well we have to be careful with time-zones if server and users are in different time zones. Otherwise user's will see different random number before user's day is complete. Please improve answer by commenting on it and suggestions are always welcome.