Hi aspsun11,
To run JavaScript code on browser close follow the below steps.
1. After successfull Login set Session variable to identify the user. In the example i have used IsValidLogin and UserId.
2. Then create a JavaScript function to make AjaxCall to a page on browser close.
3. Then call the JavaScript function and pass the required parameter.
Check this example. Now please take its reference and correct your code.
JavaScript
function AjaxCall(userId) {
var webUrl = 'Delete_Record.aspx?UserID=' + userId;
var xmlHttpObject = null;
try {
// Firefox, Opera 8.0+, Safari...
xmlHttpObject = new XMLHttpRequest();
}
catch (ex) {
// Internet Explorer...
try {
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex) {
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if (xmlHttpObject == null) {
window.alert('AJAX is not available in this browser');
return;
}
xmlHttpObject.open("GET", webUrl, false);
xmlHttpObject.send();
}
Login.aspx
<asp:Button Text="Login" runat="server" OnClick="Validate" />
Login.aspx.cs
protected void Validate(object sender, EventArgs e)
{
// If Valid Login.
if (1 == 1)
{
Session["IsValidLogin"] = true;
Session["UserId"] = "12345";
Response.Redirect("~/Default.aspx");
}
}
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="BrowserCloseCall.js" type="text/javascript"></script>
<script type="text/javascript">
window.onunload = function () {
AjaxCall('<%= Session["UserID"] %>');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Namespaces
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
Delete_Record.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
// If user logged in.
if ((bool)Session["IsValidLogin"])
{
// If UserId is exists.
if (!string.IsNullOrEmpty(Request.QueryString["UserID"]))
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM Table WHERE UId = @UserId"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@UserId", Request.QueryString["UserID"]);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
After login IsValidLogin and UserId is set and redirect to Default page.
When user close browser AjaxCall is executed inside window.onunload function and Session["UserID"] is passed and Delete_Record page called and record deleted from table.