Ajax Course

To make an Ajax request when the page is closed, apply the beforeunload event on the "window" object to call an Ajax function when the event is emited.
- The ajax request must be made synchronous.
<script>
// sends data to a php file, via POST, when page is closed
function pageClosed() {
 var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); // XMLHttpRequest object
 var data ='name=val'; //data with name and value to send to your_script.php
 request.open('post', 'your_script.php', false); //false - to make synchronous request

 request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
 request.send(data); //sends data

 console.log(data); //for debug to see if code is executed
 return true;
}

//register event eimted when page is closed, it calls the pageClosed() function
window.addEventListener('beforeunload', pageClosed);
</script>
- In the php script called by the Ajax function you should use the ignore_user_abort(true); function. It allows the php script to run on server even if the browser is closed.
 

Register the time users spend on website

Here is a practical application of the code above.
The following script registers into a file on server the time the users spend on website (in json format). Here the user is the user's IP.

1. Add the following ajax script in the pages of your website:
<script>
var start_time = Math.floor(Date.now() /1000);


// sends to php the number of seconds the user spend on time
function pageClosed() {
 var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); // XMLHttpRequest object
 var data ='tms='+(Math.floor(Date.now() /1000) - start_time); //data to send to reg_time.php
 request.open('post', 'reg_time.php', false); //false - to make synchronous request

 request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
 request.send(data); //sends data

 console.log(data); //for debug to see if code is executed
 return true;
}

//register event eimted when page is closed, it calls the pageClosed() function
window.addEventListener('beforeunload', pageClosed);
</script>
2. Add this code into a "reg_time.php" file:
<?php
ignore_user_abort(true);

if(isset($_POST['tms'])){
 $tms = intval($_POST['tms']);
 $user = $_SERVER['REMOTE_ADDR']; //here we use the ip
 $file ='reg_time.json';
 $f_data =[];

 //add the $user and $tms in json format in $file
 if(!file_exists($file)){
 $f_data[$user] = $tms;
 } else {
 $f_data = json_decode(file_get_contents($file), true);
 if(isset($f_data[$user])) $f_data[$user] = $f_data[$user]+ $tms;
 else $f_data[$user] = $tms;
 }

 file_put_contents($file, json_encode($f_data));
}
3. This php code can be used to read and show data stored in "reg_time.json":
<?php
$file ='reg_time.json';
$f_data =[];

if(file_exists($file)) $f_data = json_decode(file_get_contents($file), true);

foreach($f_data as $k=>$v){
 echo '<br>'. $k.' = '.$v.' seconds';
}

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which HTML element can be used to embed a SWF flash content?
<object> <div> <script>
<object type="application/x-shockwave-flash" data="file.swf" width="500" height="250">
 <param name="src" value="file.swf" />
 Your browser not support SWF.
</object>
Which CSS pseudo-class adds a style to an input form field that has keyboard input focus?
:active :focus :hover
input:focus {
  background-color: #88fe88;
}
Click on the instruction which converts a JSON string into a JavaScript object.
JSON.stringify(javascript_object) object.toString() JSON.parse(json_string)
var jsnstr = '{"url": "http://coursesweb.net/", "title": "Web Development Courses"}';
var obj = JSON.parse(jsnstr);
alert(obj.url);
Indicate the PHP function which can be used to create or write a file on server.
fopen() file_put_contents() file_get_contents()
if (file_put_contents("file.txt", "content")) echo "The file was created";
else echo "The file can not be created";
Ajax request when the page is closed

Last accessed pages

  1. Using v-model in form input fields (1051)
  2. jQuery UI draggable - Drag elements (11445)
  3. Display data from PHP Array, or MySQL in HTML table (26980)
  4. Redirects (4978)
  5. jsSHA - SHA Hashes and HMAC in JavaScript (3519)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (310)
  2. The Mastery of Love (48)
  3. CSS cursor property - Custom Cursors (36)
  4. Read Excel file data in PHP - PhpExcelReader (35)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (31)