Save (Insert) Logout time if browser closed accidently using jQuery Ajax in ASP.Net

nagaraju60
 
on Feb 05, 2016 05:25 AM
Sample_160640.zip
4504 Views

Hai All

http://www.aspforums.net/Threads/408364/Solved-Save-Insert-Logout-Time-on-Browser-Close-in-ASPNet/

 

by using above query its fine to save logout time in database, if the user unfortunately close the browser without logout then how to store logout time in database
could you please any body help me..

Thanks in advance

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Feb 05, 2016 06:00 AM
on Sep 13, 2017 06:40 AM

Refer the below code only works with chrome and ie.

SQL

CREATE TABLE [dbo].[UserSessionEndTime](
    [UserId] [int] NOT NULL,
    [TimeOutTime] [datetime] NULL
)

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        function doUnload() {
            $.ajax({
                type: "POST",
                url: "WebForm1.aspx/InsertLogOutTime",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    alert(r.d);
                },
                error: function (r) {
                    alert(r.responseText);
                },
                failure: function (r) {
                    alert(r.responseText);
                }
            });
        }
    </script>
</head>
<body onunload="doUnload()">
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

Code

[WebMethod]
public static void InsertLogOutTime()
{
    string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO UserSessionEndTime VALUES(@UserId,@TimeOutTime)", con))
        {
            con.Open();
            cmd.Parameters.AddWithValue("@UserId", 1);
            cmd.Parameters.AddWithValue("@TimeOutTime", DateTime.Now);
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

Screenshot