-2

I want to know what should I do to receive and post data with php frequently . What exactly I want is to receive and post an integer variable that changes every second randomly from a server to a client and at the client side print the value of my variable and update it every second . This issue is used for multiplayer games too . like a variable that holds a charecter position on the page and sends and receives the itself and other player position values . I have heard something about socket programming that solves this problem but I didn't find any good source for this issue . can you help me to how to this .

Diesel
  • 27
  • 3
  • http://socketo.me/ – vuryss Jun 19 '18 at 12:52
  • [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)? [Sockets](https://stackoverflow.com/questions/1736382/how-to-use-sockets-in-javascript-html)? AJAX (with interval)? – Script47 Jun 19 '18 at 12:54
  • This question is too broad, where did you research for this? – Script47 Jun 19 '18 at 12:56
  • you can use Ajax for fetch data every second. [ajax-jquery-refresh-div-every-5-seconds](https://stackoverflow.com/questions/25446628/ajax-jquery-refresh-div-every-5-seconds) – amrezzd Jun 19 '18 at 13:25

1 Answers1

0

The best way is use socket. Anyway I had developed a similar thing with the time.

This code update the client time with the server time every second:

----------- time.php ------------

echo("{'time' : '".date('D M d Y H:i:s')."'}");

-------- getTimeEverySec.js ----------

function startTime(){
     httpRequest= new XMLHttpRequest();
     httpRequest.open("GET", "time.php",true);
     httpRequest.onreadystatechange=timeLoaded;
     httpRequest.send();
}

function timeLoaded(){
     readyState=httpRequest.readyState;
     if(readyState!=4) return;

     status=httpRequest.status;
     if(status!=200) return;

     serverTime=httpRequest.responseText;
     eval("currentime="+serverTime); //the server side variable is stored in currentime

     var today=new Date(currentime.time);
     hours= today.getHours();
     mins = today.getminutes();
     secs = today.getSeconds();

     document.getElementById("time").innerHTML=h+":"+m+":"+s;
     var t=setTimeout(starTime,500); //recall the function every 0.5 sec
}

-------page.html--------

<H1>Current time</H1>
<p id="time"></p>

summing up: this code get every second the time from the server. The variable that is "frequently" recieved is the current server time. You can use this example to recieve any variable. Replace the

echo("{'time' : '".date('D M d Y H:i:s')."'}");

with the variable that u want recieve frequently and change a bit the javascript code

I hope I was clear.

Save
  • 38
  • 4