0

I've been trying to send an email whenever a user is trying to quit the page, i have used the beforeunload event in jQuery.

jQuery Code:

 $(window).on("beforeunload", function(e) {
     console.log('posting');
     $.post("file.php", {
             d: logData,
             s: 'New User Activity',
             t: 'example@gmail.com',
             r: 'From: info@address.com\r\n',
      },
      function(data, status) {
        console.log(data);
      );
 });

This code always logs successfully the response from file.php unless i'm using the mail() function, btw it only doesn't console.log whatever after the mail() function.

file.php contents:

<?php
$fo = fopen("file.txt","a");
fwrite($fo,"Contents:\n".$_POST['d']."\nSubject: ".$_POST['s']."\nTo:".$_POST['t']);
fclose($fo); // THIS WORKS SUCCESSFULLY

mail("example@domain.com","Subject","Msg"); //I changed this to static values so i check if the problem
//is coming from the POST, but still no success

echo "fine"; //THIS DOESN'T SHOW UP IN THE CONSOLE
?>
TarangP
  • 2,711
  • 5
  • 20
  • 41
Yak0d3
  • 1
  • 3
  • See [this](https://stackoverflow.com/a/42914045/965834). You may want to use a synchronous request in your case (see `async: false` in jQuery's docs). – Jeto Mar 03 '18 at 08:20
  • 1
    Thank you @Jeto that was the solution, please write your comment in the answer box so i can approve it – Yak0d3 Mar 03 '18 at 08:30

1 Answers1

0

See this answer.

Basically, anything asynchronous in the beforeunload might not execute, depending on when your browser actually unloads the page.

Try using a synchronous request in your case, by passing async: false to your call (docs here).

Jeto
  • 14,596
  • 2
  • 32
  • 46