Ajax post onbeforeunload doesn't work

This code stores mouse movement coordinates in array and it should post it onbeforeunload. But it doesn't post. If I change

name: moves
name: "blabla"

it works. Means that the problem is on the "moves" variable. How can I make it working ?


var moves = [];

moves.push(e.pageX + "x" + e.pageY) 

window.onbeforeunload = function() {


      type: "POST",
      url: "mailyaz.php",
      data: {
      name: moves;





You can try this. It's a little example that I develop some months ago. In this case the coordinates are stored in a Text File, but you can replace this with an INSERT into a DataBase.

On the client Side put this:

    var moves = ""; //Now an String to store the Coords

        //When you moves the mouse inside the Page then 
        //concat the Coords into the String var and add a Line-Brak at the end
            moves += (e.pageX + " x " + e.pageY + "\n");


        //Here the magic happen: bind a function to onbeforeunload event that POST
        //the String to the server
        $(window).bind('beforeunload', function() {




Now you need a Page in the server side called server.php which contains

    //Capture the String
    $cursorMoves = ($_POST['name']);

    $myFile = "testFile.txt";
    $fh = fopen($myFile, 'w');
    fwrite($fh, $cursorMoves);

onbeforeunload must return a string. However, the ajax request will be blocked by the dialog that is displayed. If the user accepts and leaves the page, it is likely that the request would be interrupted.




Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.