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.
Related
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.
I have an ordinary html table in which each cell contains a name. I've added a function to each of these cells, which turns the cells background color green, if it's white and the other way around. However, I would also like to update an mySql datebase, when a cell is clicked, but I can't seem to figure out a good way to do this, without reloading the page (which I would prefer not to do) or using javascript to connect to the server (which seems like a very bad practice). The page has already been loaded at this point. Does anybody have any good suggestions?
<script type="text/javascript">
var tbl = document.getElementById("table");
if (tbl != null) {
for (var i = 1; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
if(cel.style.backgroundColor == "green")
{
cel.style.backgroundColor = "white";
// Here I would like to update my datebase with mySql
// query(UPDATE team SET attended=0 WHERE name = cel.innterText)
// (name associated with the cell)
}
else
{
cel.style.backgroundColor = "green";
// Here I would like to update my datebase with mySql
// query(UPDATE team SET attended=1 WHERE name = cel.innterText)
// (name associated with the cell)
}
}
</script>
In broad terms, you need to turn part of your application into a service and have calls to it made by an asynchronous HTTP request from your page (this falls under the "AJAX" denomination).
That service can be written as an extra PHP script on your server, which may not necessarily return an HTML document, but possible XML or JSON (the latter is probably more popular these days), which will be handled by your JavaScript script in the browser for further actions if necessary (e.g. turning the background white only if this request has succeeded).
It is this PHP script that should handle the SQL queries.
As a general guideline, don't prepare or handle any SQL at all on the client side (in your JavaScript script), and make sure you use prepared statements when running your SQL queries. (I'm just saying that because you're obviously new to this and you'll inevitably find snippets of code here or on various blogs where people just put the variables they in into their SQL statements by using the variable in the query strings. This is extremely bad practice.)
EDIT:
I actually need to go no further than W3Schools to have a bad example of MySQL query that is vulnerable to SQL injection (the problem is in $sql="SELECT * FROM user WHERE id = '".$q."'";). DO NOT USE THIS EXAMPLE. I'd avoid W3Schools, see http://www.w3fools.com/
SQL is server side, not client side. You need to use AJAX to send data to your server and then the server will use SQL to save.
UPDATE: Seems like I have been wasting my time to some extent as according to http://www.browserscope.org/?category=network&v=top-d most modern browsers already limit the number of connections to a single host. 6 being the common number of connections which suits my purposes rather well. But I guess it is still an interesting problem.
The final piece of the jigsaw for my work task is break a list of potentially 250+ ajax requests into batches.
As the result of the following php code
<?
// print("alert(\" booya \");");
$hitlist = array();
$hitlist = urlBuilder($markets,$template);
foreach ($hitlist as $mktlist) {
foreach ($mktlist as $id => $hit) {
$cc = substr($id,0,2);
$lc = substr($id,-4);
echo ("$(\"#" . $cc . $lc . "\").load(\"psurl.php?server=" . $server . "&url=" . $hit . "&port=" . $port . "\");\n");
}
}
?>
This generates a long list of jquery .load's which right now are all executed on a click.
e.g.
$("#sesv-1").load("psurl.php?server=101.abc.com&url=/se/sv&port=80");
$("#sesv-2").load("psurl.php?server=101.abc.com&url=/se/sv/catalog/&port=80");
$("#sesv-3").load("psurl.php?server=101.abc.com&url=/se/sv/catalog/products/12345678&port=80");
$("#atde-1").load("psurl.php?server=101.abc.com&url=/at/de&port=80");
$("#atde-2").load("psurl.php?server=101.abc.com&url=/at/de/catalog/&port=80");
$("#atde-3").load("psurl.php?server=101.abc.com&url=/at/de/catalog/products/12345678&port=80");
$("#benl-1").load("psurl.php?server=101.abc.com&url=/be/nl&port=80");
$("#benl-2").load("psurl.php?server=101.abc.com&url=/be/nl/catalog/&port=80");
$("#benl-3").load("psurl.php?server=101.abc.com&url=/be/nl/catalog/products/12345678&port=80");
$("#befr-1").load("psurl.php?server=101.abc.com&url=/be/fr&port=80");
$("#befr-2").load("psurl.php?server=101.abc.com&url=/be/fr/catalog/&port=80");
$("#befr-3").load("psurl.php?server=101.abc.com&url=/be/fr/catalog/products/12345678&port=80");
Depending on circumstances it can be like 250 requests or perhaps only 30-40. The whole purpose of the app is to warm up newly restarted appservers... so 250 requests in a new jvm = death!
So ideally I would like to break them up. Perhaps by the market would be best meaning at most 5-6 requests at a time.
Any ideas on how this can be accomplished? Is it possible in standard jquery? Trying to make the dependencies as limited as possible so preferably without plugins!
You can use jQuery's .queue.
// Define a queue for execution
var
$elem = $("#sesv-1"),
enqueue = function(a){ $elem.queue("status", a) };
// Queue your requests
enqueue(function(a){
$aElem.load("url", a);
});
enqueue(function(a){
$otherElem.load("url", a);
});
// Execute the queue
$elem.dequeue("status");
You can create as many queues as you need (most probably per market) then enqueue your requests.
Ok,
I've seen a couple of solutions out there but I am looking for the most lightweight version to accomplish this following:
<?php
$number = 20;
$counter = 0;
$i = 1;
$friends = $facebook->api('/me/friends');
foreach($friends['data'] as $friend)
{
if ($counter++ == $number) {
break;
}
echo '<li id="'.$i++.'"><img src="http://graph.facebook.com/'.$friend['id'].'/picture"/>'.$friend['name'].'</li>';
}
?>
I want to be able to increase $number = 20 when the user scrolls past a speecific div.
So for instance I know I can use jQuery for the scrolling mechanism:
<script>
$('#20').waypoint(function(event, direction) {
if (direction === 'down') {
"Increase php variable to 40"
};
});
</script>
If you guys can provide any knowledge it would be much appreciated.
Thanks!
PHP runs server sided, meaning that the whole page gets computed before outputting. What you are doing is not possible the way you are approaching it.
There are two approaches that will work in this situation:
Output all the information to begin with, but hide it and when the user scrolls to whatever point show it programatically with Javascript
Use AJAX to do dynamic page generation.
AJAX allows you to make requests to the server from Javascript to request remote content. For example, you could grab the content of myFile.php?count=123 and output the result in a div.
See http://www.w3schools.com/ajax/ajax_example.asp for an example on how to use AJAX.
I have question regarding accessing all browser cookies using javascript, i was able to do this in shell script but i want to access the cookie information stored in local machine which needs to pass to server.
Regards
You can access them using
document.cookies
You cannot access all browser cookies. Only cookies set for the current domain and not marked 'http-only' (or 'secure' if you are on a non-SSL page).
In javascript use document.cookies
Update
The browser has built in functionality, as a security feature, to prevent you from reading cross domain cookies. As long as the javascript runs in the browser, there is no method to access those cookies, let alone execute a shell command. Google for: same origin policy.
What you basically are looking for has so many security/privacy implications, I don't even know where to start explaining the dangers.
Imagine that was possible. You browse to an arbitrary site that loads third-party ads, a rogue ad reads all your browser cookies and, voilá!, some guy from the Russian Mafia has the "Remember me" cookies and session IDs for all your sites. He can read your e-mail, see your pics on Facebook and retrieve money from your PayPal account.
function getCookie(name) {
// Split cookie string and get all individual name=value pairs in an array
var cookieArr = document.cookie.split(";");
// Loop through the array elements
for (var i = 0; i < cookieArr.length; i++) {
var cookiePair = cookieArr[i].split("=");
/* Removing whitespace at the beginning of the cookie name
and compare it with the given string */
if (name == cookiePair[0].trim()) {
// Decode the cookie value and return
return decodeURIComponent(cookiePair[1]);
}
}
// Return null if not found
return null;
}
function listCookies() {
var theCookies = document.cookie.split(';');
var aString = '';
for (var i = 1 ; i <= theCookies.length; i++) {
aString += i + ' ' + theCookies[i-1] + "\n";
}
return aString;
}