Wolfgang
Wolfgang

Reputation: 1398

Record and store mouse movements

My requirements are that every time a user enters the page the mouse movements start to get recorded and once the user leaves the page, all the data (Coords x, y and time) gets sent to a server for later analysis.

Upvotes: 9

Views: 14790

Answers (2)

Manwal
Manwal

Reputation: 23816

unload()

Javascript:

document.onmousemove = function(e){
  var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
  console.log(pageCoords);
};

DEMO

Unload javascript:

window.onunload=function(){
  //SomeJavaScriptCode
};

jQuery:

var pageCoords = []; //array for storing coordinates
$(document).onmousemove = function(e){
  pageCoords.push("( " + e.pageX + ", " + e.pageY + " )");//get page coordinates and storing in array
}
$( window ).unload(function() {
  //make ajax call to save coordinates array to database
});

UPDATED DEMO

Upvotes: 12

Bradly Spicer
Bradly Spicer

Reputation: 2318

One but very bad way is tracking the location of the mouse and constantly placing the position into the mysql db

(function() {
    window.onmousemove = handleMouseMove;
    function handleMouseMove(event) {
        event = event || window.event; // IE-ism
        // event.clientX and event.clientY contain the mouse position
    }
})();

Have a read of this:

Determine mouse position outside of events (using jQuery)?

and this:

Javascript - Track mouse position

Once you have read them, you'l be able to see that data is being shown in your console. Now we need to send it from the console to PHP and then into mysql.

The following explains how: http://www.coderslexicon.com/the-basics-of-passing-values-from-javascript-to-php-and-back/

Lastly, I suggest reading up on:

http://php.net/manual/en/mysqli.query.php

Don't use MySQL queries. Use MySQLi as MySQL is deprecated.

Upvotes: 1

Related Questions