想要在退出时与服务器连接。 我可以设置任何形式的Javascript / jQuery / AJAX陷阱吗?

First things first. I'm running CodeIgniter on a PHP/MySQL site.

I've been tasked with creating a "shell" application for a series of movies that a person can view for a training website that I'm building. The idea here is that a person would be able to log on to a page, click "Take Course" and have it log what time the course was taken. Then, when the person exits the page carrying the movie, I would be able to record what time the course was ended. This way I can compare the start and end times, and determine if the user had viewed most of the film in order to give the user credit. Well, the first part is easy. First, I've built a table in my database with the following fields:

  • intKey (intKey(10))
  • strHash (varchar(255))
  • dtBegan (datetime)
  • dtEnded (datetime)
  • varIpAddress (varchar(255))

I've put in a controller that does this:

$ip_address = $_SERVER['REMOTE_ADDR'];
$data['hash'] = md5(time() . "Proof of Concept!");
$this->db->query("INSERT INTO pocTime SET strHash = '" . $data['hash'] . "', dtBegan = now(), varIpAddress='$ip_address'");
$this->load->view('welcome_message',$data);

OK... easy enough, yes? I also know that when I am done, I want to launch a file that does this:

$ip_address = $_SERVER['REMOTE_ADDR'];
$this->db->query("UPDATE pocTime SET dtEnded = now() WHERE strHash = '" . $data['hash'] . "' AND varIpAddress='$ip_address'");

What I'm hoping to do is have a page that is called by the 1st block of code, and set a "trap" so to speak so that the 2nd block of code is run by some kind of "post back" if the rendered page is closed. Any suggestions? I know that I could put some sort of big "CLICK HERE TO END YOUR VIDEO" type button that would cover this, but I'm looking to run code on some form of exit from a page, because I don't know what the user would do after viewing the video. Any thoughts?

Simple but should work, using jQuery

$(window).unload(function(){
    $.get("test.php?dim1=turn&dim2=off");
});

Using unload which jQuery documentation tells what triggers this: http://api.jquery.com/unload/

Using get which jQuery documentation is here: http://api.jquery.com/get/

Or you can use post as well

$(window).unload(function(){ 
    $.post("test.php", { dim1: "turn", dim2: "off" } ); 
});

http://api.jquery.com/jQuery.post/

You are looking for jQuery's unload event.

I would also recommend that you use Codeigniter's Active Record Syntax in your database queries. Not only does it make writing INSERT and UPDATE queries much easier, it will also escape and sanitize your input to protect you from SQL injection.