I'm trying to implement the sample code on this page:
http://docs.phonegap.com/en/2.9.0/cordova_media_capture_capture.md.html#CaptureImageOptions
under capture.capture.Video (Full Example)
I've changed "cordova-x.x.x.js" to "cordova.js" (that seems to be how this distro names the file) and the server to my local Mac.
I can upload video files to the server from another PC on the same network, but when I run this code from Xcode on my tethered iPhone 4S (6.1.3) I can see the file being temporarily written to the /private/var/tmp/ folder but it is not moved to the webserver folder; it just disappears. (When I do this from the other PC, I can see it written temporarily and then sucessfully moved and renamed.)
This is the code from that example page:
<!DOCTYPE html>
<html>
<head>
<title>Capture Video</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureVideo() {
// Launch device video recording application,
// allowing user to capture up to 2 video clips
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://192.168.0.3/~me/index.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
</script>
</head>
<body>
<button onclick="captureVideo();">Capture Video</button> <br>
</body>
</html>
This is my PHP:
<?php
if (!empty($_FILES))
{
$file_src = 'video/'.$_FILES['image']['name'];
if(move_uploaded_file($_FILES['image']['tmp_name'], $file_src)):
echo 'Your file has been uploaded sucessfully';
else:
echo 'Error';
endif;
}
?>
Any idea of what I am doing wrong?
Thanks
OK, this code worked on the webserver:
<?php
$file_src = "new.mov";
move_uploaded_file($_FILES["file"]["tmp_name"], $file_src);
?>
...though I'm not sure what part of the PHP wasn't working.
Related
I have created a chatbot using chatscript. It works perfectly in .cmd when I execute a chatscript.exe program.
Now I am trying to run the chatbot the browser using xampp.
I have done the following steps:
I have installed XAMPP on C drive.
In XAMPP > HTDOCS folder I have added the Chatscript folder in it.
I am using Better web interface provided by chatscript.
When I try to run the index.php file, the bot doesn't reply.
Please find below code used in the web interface.
Index.php
<!DOCTYPE HTML>
<html>
<head>
<title> CHATSCRIPT SERVER
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
#responseHolder {
min-width: 600px;
min-height: 300px;
width: 80%;
height: 300px;
overflow: auto;
margin: 10px auto;
background-color: pink;
}
</style>
</head>
<body class="bgimg">
<div id="responseHolder"></div>
<form id="frmChat" action="#">
<p>
Enter your message below:
</p>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="txtUser" name="user" size="20" value="" />
<input type="hidden" name="send" />
</td>
</tr>
<tr>
<td>Message:</td>
<td><input type="text" name="message" id="txtMessage" size="70" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="send" value="Send Value" /></td>
</tr>
</table>
</form>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var botName = 'rose'; // change this to your bot name
// declare timer variables
var alarm = null;
var callback = null;
var loopback = null;
$(function(){
$('#frmChat').submit(function(e){
// this function overrides the form's submit() method, allowing us to use AJAX calls to communicate with the ChatScript server
e.preventDefault(); // Prevent the default submit() method
var name = $('#txtUser').val();
if (name == '') {
alert('Please provide your name.');
document.getElementById('txtUser').focus();
}
var chatLog = $('#responseHolder').html();
var youSaid = '<strong>' + name + ':</strong> ' + $('#txtMessage').val() + "<br>\n";
update(youSaid);
var data = $(this).serialize();
sendMessage(data);
$('#txtMessage').val('').focus();
});
// any user typing cancels loopback or callback for this round
$('#txtMessage').keypress(function(){
window.clearInterval(loopback);
window.clearTimeout(callback);
});
});
function sendMessage(data){ //Sends inputs to the ChatScript server, and returns the response- data - a JSON string of input information
$.ajax({
url: 'ui.php',
dataType: 'text',
data: data,
type: 'post',
success: function(response){
processResponse(parseCommands(response));
},
error: function(xhr, status, error){
alert('oops? Status = ' + status + ', error message = ' + error + "\nResponse = " + xhr.responseText);
}
});
}
function parseCommands(response){ // Response is data from CS server. This processes OOB commands sent from the CS server returning the remaining response w/o oob commands
var len = response.length;
var i = -1;
while (++i < len )
{
if (response.charAt(i) == ' ' || response.charAt(i) == '\t') continue; // starting whitespace
if (response.charAt(i) == '[') break; // we have an oob starter
return response; // there is no oob data
}
if ( i == len) return response; // no starter found
var user = $('#txtUser').val();
// walk string to find oob data and when ended return rest of string
var start = 0;
while (++i < len )
{
if (response.charAt(i) == ' ' || response.charAt(i) == ']') // separation
{
if (start != 0) // new oob chunk
{
var blob = response.slice(start,i);
start = 0;
var commandArr = blob.split('=');
if (commandArr.length == 1) continue; // failed to split left=right
var command = commandArr[0]; // left side is command
var interval = (commandArr.length > 1) ? commandArr[1].trim() : -1; // right side is millisecond count
if (interval == 0) /* abort timeout item */
{
switch (command){
case 'alarm':
window.clearTimeout(alarm);
alarm = null;
break;
case 'callback':
window.clearTimeout(callback);
callback = null;
break;
case 'loopback':
window.clearInterval(loopback);
loopback = null;
break;
}
}
else if (interval == -1) interval = -1; // do nothing
else
{
var timeoutmsg = {user: user, send: true, message: '[' + command + ' ]'}; // send naked command if timer goes off
switch (command) {
case 'alarm':
alarm = setTimeout(function(){sendMessage(timeoutmsg );}, interval);
break;
case 'callback':
callback = setTimeout(function(){sendMessage(timeoutmsg );}, interval);
break;
case 'loopback':
loopback = setInterval(function(){sendMessage(timeoutmsg );}, interval);
break;
}
}
} // end new oob chunk
if (response.charAt(i) == ']') return response.slice(i + 2); // return rest of string, skipping over space after ]
} // end if
else if (start == 0) start = i; // begin new text blob
} // end while
return response; // should never get here
}
function update(text){ // text is HTML code to append to the 'chat log' div. This appends the input text to the response div
var chatLog = $('#responseHolder').html();
$('#responseHolder').html(chatLog + text);
var rhd = $('#responseHolder');
var h = rhd.get(0).scrollHeight;
rhd.scrollTop(h);
}
function processResponse(response) { // given the final CS text, converts the parsed response from the CS server into HTML code for adding to the response holder div
var botSaid = '<strong>' + botName + ':</strong> ' + response + "<br>\n";
update(botSaid);
}
</script>
</body>
</html>
ui.php
<?php
// ============= user values ====
$host = "localhost"; // <<<<<<<<<<<<<<<<< YOUR CHATSCRIPT SERVER IP ADDRESS OR HOST-NAME GOES HERE
$port = 8080; // <<<<<<< your port number if different from 1024
$bot = "rose";
// <<<<<<< desired botname, or "" for default bot
//=========================
// Please do not change anything below this line.
$null = "\x00";
$postVars = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
extract($postVars);
if (isset($send))
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$userip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$userip = $_SERVER['REMOTE_ADDR'];
}
$msg = $userip.$null.$bot.$null.$message.$null;
if(!$fp=fsockopen($host,$port,$errstr,$errno,300))
{
trigger_error('Error opening socket',E_USER_ERROR);
}
// write message to socket server
fputs($fp,$msg);
while (!feof($fp))
{
$ret .= fgets($fp, 512);
}
fclose($fp);
exit($ret);
}
Please find below screenshot of the issue:
Issue while accessing chatbot on localhost:8080
I am having difficulty in connecting my chatscript server and localhost. Please let me know what should I change in UI.php so that bot will send the reply.
Thanks in advance.
There is one error in the UI.php file. The $ret variable breaks because it is not declared. If you add $ret = ''; just above fputs the code should work:
// write message to socket server
$ret = '';
fputs($fp,$msg);
while (!feof($fp))
{
$ret .= fgets($fp, 512);
}
fclose($fp);
exit($ret);
}
Besides the $ret correction, upon running in XAMPP, as the web host is Apache, so client uses port 8080 or 8088, upon using CS over Web.
ChatScript as server, start the ChatScript system with using port 1024 ( or user-defined) is needed.
Furthermore, Harry Bot is also called in index.php file, change to Rose as in ui.php file.
I have CS responses after doing these.
I've implemented long polling mechanism using XMLHttprequest. My problem is that after the browser is closed, the server side process continues to run and doesn't shutdown.
The web server is httpd apache and the process is a php script .
I do want the php script to close after the browser closes .
i discovered that php doesn't discover connection close unless it tries to output data back to the browser .
this is a problem, since it will compromise the objective of minimizing bandwidth usage .
the client side script, uses onreadystatechange to try and read partial data without requiring new XMLHttprequest for each communication .
some browsers will not allow to read partial data until the whole response is finished :
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"></meta>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(NewReq);
var mode = 0;
function NewReq() {
var Req = new XMLHttpRequest();
var url = 'a.php';
if (mode) {
url += '?mode=' + mode;
}
Req.open('GET', url);
Req.onreadystatechange = function(event) {
var handler = ReadyState[this.readyState];
if (typeof handler == 'function') {
handler(this);
}
};
inc_mycookie();
Req.send();
}
var ReadyState = [
//'NotInit', 'ReqRec', 'ConEst'
null , null, null,
partial // 'Proccessing'
,
complete //'Finishied'
];
function partial(Req) { //'Proc'
if (mode == 1) {
return;
}
try {
var strings = Req.response.split(';');
strings.pop();
var data = JSON.parse(strings.pop());
$('#message').text(data);
mode = 2;
}
catch (e) {
$('#message').text(e.message);
mode = 1;
}
return;
}
function complete(Req) {
var last = $('#message').text();
$('#output').text(last);
NewReq();
}
function inc_mycookie() {
var matches = document.cookie.match(/(?:^|;)mine=([^;]+);?/);
if (matches) {
var inc = parseInt(matches[1]) + 1;
document.cookie = 'mine=' + inc;
}
}
</script>
</head>
<body>
<h3> output </h3>
<div id="output"></div>
<h3> partial </h3>
<div id="message"></div>
</body>
</html>
and here is the php script (apache has "php_value output_buffering Off") :
<?php
header('Content-type: application/json');
if (!isset($_COOKIE['mine'])) {
setcookie('mine', 23);
$_COOKIE['mine'] = 23;
}
$mode = isset($_GET['mode']) ? $_GET['mode'] : 1;
print json_encode('test_' . $_COOKIE['mine']) . ';';
if ($mode == 2 ) {
$iter = 8;
while($iter) {
sleep(2);
$iter--;
error_log('a.php:' . $iter);
// if i remove this line, then erro_log will continue to show even when browser is closed
print json_encode('test_' . $_COOKIE['mine'] . '_' . $iter) . ';';
}
}
?>
in the case where browser support partial response, the damage is not too bad .
but if browser require the whole response to finish, then the damage will be a complete compromise of long polling, meaning a repetitive request every 5 seconds .
one possible solution is to add interval :
<?php
$iter = 200;
while($iter) {
sleep(2);
$iter--;
error_log('a.php:' . $iter);
if (update_exist()) {
print json_encode('test_' . $_COOKIE['mine'] . '_' . $iter) . ';';
}
else if (($iter-200)%20 == 0) { // 180, 160, 140 ... 40, 20, 0
print json_encode('check connection : ' . $iter) . ';';
}
}
Even though this is almost 5 years old, consider
XMLHTTPRequest.abort()
The javascript in the question would need to be redesigned in the following ways:
Make Req a global variable, so that
Req.abort() could be called, in (for instance)
window.addEventListener('unload', function() { Req.abort(); })
so that closing the page could cause the client to terminate the connection to the server.
I'm on a Linux web server. The following files are being used to create a screenshot:
ons.php
ong.js
ons2.php
All these files along with phantomJS binary are in the same folder. The folder's permission is 744
ons.php
$forMonth = date('M Y');
exec('./phantomjs ons.js '.strtotime($forMonth), $op, $er);
print_r($op);
echo $er;
ons.js
var args = require('system').args;
var dt = '';
args.forEach(function(arg, i) {
if(i == 1)
{
dt = arg;
}
});
var page = require('webpage').create();
page.open('./ons2.php?dt='+dt, function () { //<--- This is failing
page.render('./xx.png');
phantom.exit();
});
ons2.php
<!DOCTYPE html>
<html>
<head>
<title>How are you</title>
</head>
<body>
<?php
if(isset($_GET['dt']))
{
echo $_GET['dt'];
}
else
{
echo '<h1>Did not work</h1>';
}
?>
</body>
</html>
On opening ons.php in the browser, I'm getting this result:
Array ( ) 0
But no screenshot is being created.
Debugging
On debugging a lot, I found out that it has to do with paths.
--> If I put the following inside ons.js
.
.
.
var page = require('webpage').create();
page.open('http://www.abc.com/ppt/ons2.php', function () { // <-- absolute path
page.render('./xx.png');
phantom.exit();
});
The screenshot is getting created. I want to avoid using absolute paths as the application will be shifted to a different domain pretty soon.
What I don't get is why relative path is not working even if all files are in the same folder. Is my syntax of page.open('./ons2.php....') wrong?
./ons2.php implies a local file. It will not be passed through to the web server, and moreover it will fail outright because you also appended a query string - in the local file system this would be treated as part of the file name, so the file will not be located at all.
You will need to supply an absolute URL for this to work as you expect - but you can determine this dynamically in PHP (using $_SERVER) and pass it in to the JS script as a command line argument.
For example (untested):
ons.php
<?php
// Determine the absolute URL of the directory containing this script
$baseURL = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http')
. '://' . $_SERVER['HTTP_HOST']
. rtrim(dirname($_SERVER['REQUEST_URI']), '/') . '/';
$now = new DateTime('now'); // Because all the cool kids use DateTime
$cmd = './phantomjs ons.js '
. escapeshellarg($now->format('M Y')) . ' ' // Don't forget to escape args!
. escapeshellarg($baseURL)
. ' 2>&1'; // let's capture STDERR as well
// Do your thang
exec($cmd, $op, $er);
print_r($op);
echo $er;
ons.js
var args, url, page;
args = require('system').args;
if (args.length < 3) {
console.error('Invalid arguments');
phantom.exit();
}
url = args[2] + 'ons2.php?dt=' + encodeURIComponent(args[1]);
console.log('Loading page: ' + url);
page = require('webpage').create();
page.open(url, function () {
page.render('./xx.png');
phantom.exit();
});
ons2.php remains the same.
Maybe there is an issue in page.render but I don't think so. The most common case of hangs is unhandled exception.
I will suggest you 4 things to investigate the issue :
add an handler to phantom.onError and/or to page.OnError
encapsulate your code in try/catch blocks (such as for page.render)
Once the page is loaded, there is no test on callback status. It's better to check the status ('success' or 'fail')
seems to freeze when calling page.render. Have you tried a simpler filename in the current directory? Maybe the freeze is because of the security or invalid filename (invalid characters?)
Hope this will help you
Well i am trying to Test the AJAX code and running the sample Example from this book :
AJAX and PHP By: Audra Hendrix; Bogdan Brinzarea; Cristian Darie
Now there are Three Files :
1) Index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX with PHP, 2nd Edition: Quickstart</title>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
</html>
2) quickstart.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlHttp = false;
}
}
else
{
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
function process(){
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
name = encodeURIComponent(
document.getElementById("myName").value);
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
setTimeout('process()', 1000);
}
function handleServerResponse() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
helloMessage = xmlDocumentElement.firstChild.data;
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage
+ '</i>';
setTimeout('process()', 1000);
}
else {
alert("There was a problem accessing the server: " +
xmlHttp.statusText);
}
}
}
3) quickstart.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$name = $_GET['name'];
$userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don\'t know you!';
echo '</response>';
?>
But the same code is showing me the problem when i upload it into my Site: 000Webhost.com
I tried on 3 Different Browsers:
1) Google Chrome showing me No Error but the code is not running either.
2) FireFox is showing this error as:
XML Parsing Error: junk after document element Location: http://flavorsofsoul.site88.net/ajax/quickstart/quickstart.php?name= Line Number 3, Column 1:
3) And IE8 is showing this:
Webpage error details
Message: Object required
Line: 65
Char: 7
Code: 0
URI: http://flavorsofsoul.site88.net/ajax/quickstart/quickstart.js
I have tried to find the Solution from Internet but nothing was helpful. So if anyone can Provide the Solution , i shall be thankful.
Here is a port of your code using jQuery, It will poll each second and $_GET the value in the text box to the server, and dependent on that fill a json array with the name, then if the name returned is greater then 1 char replace the divMessage div with a message, hope it helps:
polling.php
<?php
if(!empty($_GET['name']) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
header('Content-type: application/json');
$userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN');
if (in_array(strtoupper($_GET['name']), $userNames)){
$data = array('name'=>$_GET['name']);
echo json_encode($data);
}else{
echo json_encode(array('name'=>''));
}
die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX Polling with jQuery & PHP (json)</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" charset="utf-8"></script>
<script>
//jQuery stuff
function poll(){
setTimeout(function(){
var name = $("#name").val();
if(name.length == 0){name = 'null';}
$.ajax({ url: "polling.php?name=" + name, cache: false,
success: function(data){
if(data.name.length >= 1){
$("#divMessage").replaceWith('<div id="divMessage">Welcome '+ data.name +'!<div>');
}else{
$("#divMessage").replaceWith('<div id="divMessage">I Dont know you.<div>');
}
poll();
}, dataType: "json"});
}, 1000);
}
$(document).ready(function(){
poll();
});
</script>
</head>
<body>
Server wants to know your name: <input type="text" id="name" />
<div id="divMessage"><div>
</body>
</html>
Ive been asking this question over and over many times in a bad way, so ill try to make it clearer.
I have a page with HTML that has an Attack and Restart Link on the page, the restart link appears after you win.
These links are JavaScript:
<script type="text/javascript">
<!--
function attack() {
window.location = "attack.php?attack=1";
}
function restart() {
window.location = "battle.php?id=1&status=start";
}
-->
</script>
I want to make it so that once the person has clicked one of these link, (using javascript) it gets the X/Y coords of where the clicked the link and inserts it into the database with the following values:
id
ip
username
x
y
restart
For the id, ip, username and restart I could easily use MYSQL and PHP, but I dont know how to insert Javascript information into the database, which would be the X/Y coords.
Using the Insterstellar_coder's X/Y javascript snippet, you could use javascript to make an ajax call to a php script. The ajax call would contain all the parameters as arguments and the php script on the server could get these arguments and do the database insertion.
Edition (20111016211256-0400): added files to show a solution (as far as I understand correctly the issue):
I've worked only the attack part. the restart part is similar.
No AJAX part was needed since I did piggyback on your attack and restart php files.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>index</title>
<script type="text/javascript" charset="utf-8">
// get continous mouse move events and keep the coordinates in tempX and tempY
// stolen from http://javascript.internet.com/page-details/mouse-coordinates.html
var IE = document.all?true:false;
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
}
else { // grab the x-y pos.s if browser is NS
tempX = e.pageX;
tempY = e.pageY;
}
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}
return true;
}
var ip = "10.0.0.1";
var username = "me";
var id = "1";
function Coordinates(x,y) {
this.x = x;
this.y = y;
}
function attack(e) {
window.location = "attack.php?attack=1&x="+tempX+"&y="+tempY+"&ip="+ip+"&username="+username+"&id="+id;
}
function restart() {
window.location = "battle.php?id=1&status=start";
}
</script>
</head>
<body id="index" onload="">
<input type="button" name="attack" value="attack" id="attack" onClick="attack();">
<input type="button" name="restart" value="restart" id="restart" onClick="restart();">
</body>
</html>
attack.php
<?php
$METHOD = '_' . $_SERVER['REQUEST_METHOD'];
foreach ($$METHOD as $key => $value) {
$$key = $value;
}
$log = array("attack" => $attack, "x" => $x, "y" => $y, "ip" => $ip, "username" => $username, "id" => $id);
//print_r($log);
try {
// assuming you use mongodb locally
$m = new Mongo();
$db = $m->mydb;
$logs = $db->logs;
$logs->insert($log, true);
} catch (Exception $e) {
echo $e;
}
?>
You can get the pageX and pageY coordinates from the event object. Here is some rough code.
$('yourlinkid').click(function(e){
var x = e.pageX; // x coordinate
var y = e.pageY; // y coordinate
});
There's an epic library for this called Touché. It gives you a lot of information about the user interaction with the page (e.g clicking, dragging). You can also specify callbacks for AJAX purposes if you want to send data to the database or maybe do something else.
Here's the demo