0

Im trying to store data of how many clicks and the amount of time a visitor spends on the site

Im sending the data to my php file with this ajax call.

window.onbeforeunload = function(){

  var endTime = new Date();  
  var timeSpent = (endTime - startTime);

  $.ajax({ 
    url: baseUrl + siteDir + pathToDataXml,
    type: "POST",
    datatype: "html",
    data: 'time='+timeSpent+'&clicks='+count,
    })
return "Thank You For Participating";
}    

the ajax call is hitting the php file as new records are being entered into the database, but the records are blank.

Any suggestions would be great

James Kirkby
  • 1,716
  • 5
  • 24
  • 46
  • in the old days it was possible, now browsers kill the requests. It is a race condition. – epascarello Nov 14 '13 at 23:05
  • Unless, you use async: false? – Kevin B Nov 14 '13 at 23:10
  • Yes, did you think about browser crashing, lost internet connection, computer went to sleep, etc? None of them would throw an unload event. The problem with false is the fear that the browser will lock up. If it is fired on every unload, your site will feel unresponsive. – epascarello Nov 14 '13 at 23:13
  • I should of said this wont be used in a public environment, this will be used as part of a user experience experiment, browser and connectivity are all controlled i added async: false which doesn't work either, what i dont understand it's not that it's not calling the ajax function because im getting empty records sent to the database and if i go to the php file its calling file.php?foo=value&foo1=value the data is submitted – James Kirkby Nov 14 '13 at 23:18

2 Answers2

0

Sometimes painfully obvious problems are the hardest as they are overlooked

If you want to send data over URL parameter $_GET should be used rather than $_POST

James Kirkby
  • 1,716
  • 5
  • 24
  • 46
-1

try this

$( window ).unload(function() {
      var endTime = new Date();  
      var timeSpent = (endTime - startTime);

      $.ajax({ 
        url: baseUrl + siteDir + pathToDataXml,
        type: "POST",
        datatype: "html",
        data: 'time='+timeSpent+'&clicks='+count,
        })
    return "Thank You For Participating";
    });
AOZ
  • 196
  • 1
  • 8