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 .
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.
Related
I am making a php chat and am starting the php checking database part. So when a user types something into the chat, it gets recorded in the MySQL database, how would I check the database every 10 seconds so that one user's chat would update with new messages from other users. I know that you can use an ajax request to a page with an interval, but I want the php to be on the same page, instead of having to use numerous pages. This is the code for checking the database
<?php
$con = mysqli_connect('host','user','pass','database');
$query = mysqli_query($con,"SELECT * FROM `messages`");
while ($row=mysqli_fetch_assoc($query)) {
$user = $row['user'];
$message = $row['message'];
echo 'User: ',$user,' Message: ',$message;
}
?>
Thanks in advance anyone!
Use MySQL Event Scheduler.
Below link will guide you through .
http://www.9lessons.info/2012/10/mysql-event-scheduler.html.
I think best option in your case .
AJAX is probably the simplest solution. You can perform an AJAX request on the same page your PHP code is executing on if you really want to.
(function check() {
$.get('mypage.php', function(data) {
doSomethingWith(data);
setTimeout(check, 5000); // every 5 seconds
});
})();
PHP doesn't have a setInterval function. While I'm sure you can use a crontask to automate it on the server, you can also achieve this with some simple Javascript.
The concept you are trying to achieve is known as Short Polling. What you want to do is to have a setInterval function in Javascript that constantly makes AJAX requests to your PHP file which performs the check to the database for new messages. Your PHP should return that information to your script where you can then simply populate the user's screen.
There is also Long Polling where you simply maintain the connection and have a setTimeout to wait for messages to come in. You can find more information yourself and if you have questions, you can come back here.
A good video about this:
https://www.youtube.com/watch?v=wHmSqFor1HU
Hope this helps.
This is what you need. We need set time for ajax auto reload. Don't put everything in one page. Because you must reload page to refresh data. That is bad solution.
Call jQuery Ajax Request Each X Minutes
Make a while for 30 seconds, and check the db every second, once you find a record the while is being broken, also it is being broken when 30 secs are expired.
$sec = 1;
while($sec <= 30) {
if(has record)
Send to the user;
$sec++;
sleep(one sec here);
}
Use sleep for 10 secs in order to check every 10 secs...
Purely hypothetical at this point, no code yet. Trying to figure out the best way to do this. We are company "A" and we have two partners, company "B" and company "C". On a sign up form, we collect data and then pass it on to either partner "B" or parnter "C" - this part is good to go and working fine. I do this with ajax on the front end and a cURL processor on the back end so no one leaves our site and just post the data directly to the partner's form.
Unfortunately due to partner "B" and "C"'s required data the forms we post to are different and we have to have 2 separate html form files, one for each partner. The problem is that we need to do this all from one URL, not a separate one for each partner.
I would guess we would use a 'handler' page that has the specific url - http://www.example.com/parterForm.php
Then in the 'handler' page we would make the switch serve the correct content. I need a way to evenly split who we send data to. I'd like to do the switch on a very granular, MS level for example:
if the time = 0-500 ms - serve Parter B page;
if time = 501-1000ms -serve Partner C page;
all done within the 'handler' page - calling the forms as php includes?
I realize this is not a specific code question and I aplogize, this is something I've never done before and am trying to figure out how to do this. I'm a Creative Director btw who codes, no other resource avail.
thanks.
Hmm, yes, you could do that. That would work reasonably well, in fact. The important thing is to make sure the form goes to the right partner. You could use $_SESSION for that, or check which fields were sent and deduce from that which partner was chosen.
For example:
if( fmod(microtime(),1) < 0.5) include("forms/partner1.php");
else include("forms/partner2.php");
Then when submitted:
$partner1fields = array("name","email","country","dateofbirth");
$partner2fields = array("name","address","postcode","ethnicity");
// the above are examples - they should correspond to the $_POST keys you expect
// now check if they match. Array equality depends on order, so sort first
$postkeys = array_keys($_POST);
sort($postkeys);
sort($partner1fields);
sort($partner2fields);
if( $postkeys == $partner1fields) { /* submit to partner 1 */ }
elseif( $postkeys == $partner2fields) { /* submit to partner 2 */ }
else {
echo "<p>Given keys did not match either partner</p>";
echo "<p>POST keys: ".implode(", ",$postkeys)."</p>";
echo "<p>Partner 1 keys: ".implode(", ",$partner1keys)."</p>";
echo "<p>Partner 2 keys: ".implode(", ",$partner2keys)."</p>";
echo "<p>Please report this error to the site administrator.</p>";
exit;
}
First, by MS I assume you mean the latency between client and server?
Use javascript to either load a tiny image from the server or make an ajax call that gets one char or something and time this. For testing you'll need to do some real pings and adjust your js time to reflect the ping round trip. For example, if the js time to load the image is 500ms but ping time is only 80ms then maybe divide by 6 for the result. This will never be very precise as the client and the server both have processing overhead. Make sure to echo no cache headers or past expire times with the image or ajax response.
Easy, if time <= 500 redirect to form A, if time > 500 redirect to form B or use ajax to load them up.
I'm looking into doing some long polling with jQuery and PHP for a message system. I'm curious to know the best/most efficient way to achieve this. I'm basing is off this Simple Long Polling Example.
If a user is sitting on the inbox page, I want to pull in any new messages. One idea that I've seen is adding a last_checked column to the message table. The PHP script would look something like this:
query to check for all null `last_checked` messages
if there are any...
while(...) {
add data to array
update `last_checked` column to current time
}
send data back
I like this idea but I'm wondering what others think of it. Is this an ideal way to approach this? Any information will be helpful!
To add, there are no set number of uses that could be on the site so I'm looking for an efficient way to do it.
Yes the way that you describe it is how the Long Polling Method is working generally.
Your sample code is a little vague, so i would like to add that you should do a sleep() for a small amount of time inside the while loop and each time compare the last_checked time (which is stored on server side) and the current time (which is what is sent from the client's side).
Something like this:
$current = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$last_checked = getLastCheckedTime(); //returns the last time db accessed
while( $last_checked <= $current) {
usleep(100000);
$last_checked = getLastCheckedTime();
}
$response = array();
$response['latestData'] = getLatestData() //fetches all the data you want based on time
$response['timestamp'] = $last_checked;
echo json_encode($response);
And at your client's side JS you would have this:
function longPolling(){
$.ajax({
type : 'Get',
url : 'data.php?timestamp=' + timestamp,
async : true,
cache : false,
success : function(data) {
var jsonData = eval('(' + data + ')');
//do something with the data, eg display them
timestamp = jsonData['timestamp'];
setTimeout('longPolling()', 1000);
},
error : function(XMLHttpRequest, textstatus, error) {
alert(error);
setTimeout('longPolling()', 15000);
}
});
}
Instead of adding new column as last_checked you can add as last_checked_time. So that you can get the data from last_checked_time to the current_time.
(i.e) DATA BETWEEN `last_checked_time` AND `current_time`
If you only have one user, that's fine. If you don't, you'll run into complications. You'll also run one hell of a lot of SELECT queries by doing this.
I've been firmly convinced for a while that PHP and long polling just do not work natively due to PHP not having any cross-client event-driven possibilities. This means you'll need to check your database every second/2s/5s instead of relying on events.
If you still want to do this, however, I would make your messaging system write a file [nameofuser].txt in a directory whenever the user has a message, and check for message existence using this trigger. If the file exists and is not empty, fire off the request to get the message, process, feed back and then delete the text file. This will reduce your SQL overhead, while (if you're not careful) increasing your disk IO.
Structure-wise, an associative table is by far the best. Make a new table dedicated to checking the status, with three columns: user_id message_id read_at. The usage should be obvious. Any combination not in there is unread.
Instead of creating a column named last_checked, you could create a column called: checked.
If you save all messages in the database, you could update the field in the database. Example:
User 1 sends User 2 a message.
PHP receives the message using the long-polling system and saves the message in a table.
User 2, when online, would send a signal to the server, notifying the server that User 1 is ready to receive messages
The server checks the table for all messages that are not 'checked' and returns them.
I'm writing a multi-user, JavaScript based drawing app as a learning project. Right now it's one way: the "transmitter" client at transmitter.html sends the data as the user draws on the HTML5 canvas element, the "receiver" client at receiver.html replicates it on their own canvas.
The transmitter just draws a line between (previousX, previousY) and (currentX, currentY) in response to a mouseMove event. It sends those two sets of coordinates to transmitter.php via AJAX. They sit in a session var until the receiver collects them by calling receiver.php, also via AJAX. At least that's how it should work.
This is transmitter.php:
<?php
session_start();
if (!isset($_SESSION['strokes'])) $_SESSION['strokes'] = '';
$_SESSION['strokes'] .= $_GET['px'] . "," . $_GET['py'] . "," . $_GET['x'] . "," . $_GET['y'] . ';';
?>
This is receiver.php:
<?php
session_start();
echo($_SESSION['strokes']);
$_SESSION['strokes'] = "";
?>
In case you're wondering why I'm using a session var, it's because it's the fastest way I could think of to store the data in such a way that it could be accessed by the other script. I tried googling for alternatives but couldn't find anything. If there's a better way, I'd love to hear about it.
Anyway, the problem is that not all of the data is making it through. This manifests itself by gaps in the lines drawn on the receiver's canvas. I also set up a little counter in the transmitter's and receiver's JavaScript files, to check exactly how many "strokes" were being sent/received. There are invariably less received than sent, so the data is being lost server-side, it seems.
At the risk of giving you more code than you need to see, this is the code in transmitter.js that sends the data to the server (n is the counter that I mentioned):
function mouseMoveHandler(e)
{
var x = e.pageX - canvasX;
var y = e.pageY - canvasY;
if (mouseDown)
{
canvas.moveTo(prevX, prevY);
canvas.lineTo(x, y);
canvas.stroke();
sendToServer(prevX, prevY, x, y);
n++;
}
prevX = x;
prevY = y;
}
This is the code in receiver that gets it back and draws it (again, n is the counter):
function responseHandler()
{
if (xhr.readyState == 4)
{
var strokes = xhr.responseText.split(';');
n += strokes.length - 1;
for (var i = 0; i < strokes.length - 1; i++)
{
stroke = strokes[i].split(',');
canvas.moveTo(stroke[0], stroke[1]);
canvas.lineTo(stroke[2], stroke[3]);
canvas.stroke();
}
setTimeout("contactServer()", 500);
}
}
If I read your question correctly; you're trying to access the same session from different clients? If this is the case, this isn't possible, sessions are bound to a client/user.
If you want something realtime, multi-user you probably should take a look at NodeJS and specifically at NodeJS Events. Which is JS based, so I think that will integrate nicely in your application.
I'm creating a site where users can bid on items in a silent auction. I want to be able to somehow start a timer and then let users bid on the items. Once the timer reaches a certain number, I want to be able to remove the bid feature on the auction items.
Does anyone know the best approach for me to do this and what functions or plugins may be helpful? I would prefer a pure PHP approach, but I imagine a mix between PHP and jQuery would most likely solve my problem somehow? Any suggestions? How can I do this?
Thank you in advance!
What I'd do is set an end date on the database entry associated with the auction. Then you just need to check if the current date is before or after the end date.
Then in the front end you can either display the difference between the end date and the current date simply or using some javascript.
Of course it is important that you check that the auction is not over in your php before doing anything since it is really easy to bypass javascript.
jQuery Countdown , This Plugin might help u
Check The "Callback Events" section , that what u need to utilized.
It's Something Like This
$('#shortly').countdown({until: shortly,
onExpiry: liftOff, onTick: watchCountdown});
$('#shortlyStart').click(function() {
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#shortly').countdown('change', {until: shortly});
});
function liftOff() {
alert('We have lift off!');
}
function watchCountdown(periods) {
$('#monitor').text('Just ' + periods[5] + ' minutes and ' +
periods[6] + ' seconds to go');
}