Monday, May 13, 2013

Update the database on browser close?

The only way is by using AJAX. Here's an example.
//////////////////////////////////////////////////////////////////////////
// Page1.aspx
//////////////////////////////////////////////////////////////////////////

<script type="text/javascript">
<!--
var g_databaseRecordKey = '<%= DatabaseRecordKey %>';
var g_isPostBack = false;
function callAjax(webUrl, queryString)
{
 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 + queryString, false);
 xmlHttpObject.send();
 var valueSent = xmlHttpObject.responseText;
 return valueSent;
}
function doUpdate()
{
 var webUrl = 'AjaxPage.aspx';
 // Add any additional values needed for the update to the QueryString...
 var queryString = '?CallRequest=UpdateDatabase&DbKey=' + g_databaseRecordKey;
 var returnCode = callAjax(webUrl, queryString);
 //alert('returnCode: ' + returnCode);
}
function windowOnUnload()
{
 if ( g_isPostBack == true )
  return; // Let the page unload
 //alert('window.onunload fired');
 doUpdate();
}
window.onunload = windowOnUnload;
// -->
</script>
//////////////////////////////////////////////////////////////////////////
// Page1.aspx.cs
//////////////////////////////////////////////////////////////////////////

protected string DatabaseRecordKey = "";
protected void Page_Load(object sender, EventArgs e)
{
 // Set to the unique database record key for this user...
 DatabaseRecordKey = "1234";
 this.ClientScript.RegisterOnSubmitStatement(this.GetType(), "OnSubmitScript", "g_isPostBack = true;");
}
//////////////////////////////////////////////////////////////////////////
// AjaxPage.aspx.cs
//////////////////////////////////////////////////////////////////////////

protected string UpdateDatabase(string dbKey)
{
 string returnValue = "OK";
 // Update the database here setting the returnValue variable to "Failed" if not successful...
 return returnValue;
}
private void Page_Load(object sender, System.EventArgs e)
{
 string callRequest = (this.Request["CallRequest"] == null) ? string.Empty : this.Request["CallRequest"];
 string returnValue = string.Empty;
 if ( callRequest == "UpdateDatabase" )
 {
  string dbKey = (this.Request["DbKey"] == null) ? string.Empty : this.Request["DbKey"];
  returnValue = UpdateDatabase(dbKey);
 }
 this.Response.ClearHeaders();           
 this.Response.Clear();
 this.Response.Write(returnValue);
 this.Response.End();
}

0 comments:

Post a Comment