如何在页面关闭之前发送ajax数据?

I want to send a value to the database when the user closes the page such as online and offline , I hope to find the solution I have tried for more than 7 hours But does not work

<script tysssspe="text/javascript">
//ST
window.onbeforeunload = function(){
  var user_st = "0";
  $.ajax({
    type:"POST",url:"inc/offline.php",
    data:"user_st="+user_st
  });
}
//SD
</script>

To offline.php

<?php
tab
include "connect.php";
$UID = $_COOKIE["ID"];
$online_status = $_POST['user_st'];
$setStatus = $conn->prepare("UPDATE accounts SET online = :online_status WHERE id = :UID");
$setStatus->bindParam(':online_status',$online_status,PDO::PARAM_INT);
$setStatus->bindParam(':UID',$UID,PDO::PARAM_INT);
$setStatus->execute();
?>

onbeforeunload will work in some browser (Chrome), but not in others. (Safari , FF and IE).

There was a workaround is to make the ajax synchronous,

window.onbeforeunload = function(){
  var user_st = "0";
  $.ajax({
    type:"POST",url:"inc/offline.php",
    data:"user_st="+user_st,
    async: false
  });
}

but Synchronous Ajax is deprecated. You can try if you can accept deprecated methods.

If you doesn't require the online/offline to be 100% real time, one solution could be instead of reporting offline, let the user to report online (every 30 seconds, if server doesn't receive online update for more than 30 seconds, it treats this user as offline.) Potential disadvantage is that more db calls. (Do you need it to be persisted to database? Can it be in memcache? )

In your ajax call, try using an absolute URL instead of a relative one. Ex: /inc/offline.php