Why is my onbeforeunload not running now when it was before? Or AJAX failing on second identical command?

StackOverflow https://stackoverflow.com/questions/564676

  •  05-09-2019
  •  | 
  •  

Question

This follows on from this question

This was working:

<body onbeforeunload=
 "ajaxRequest('UnlockQuery.ashx?QueryID=266&UserID=11631');"> 

This was created using the following in the aspx page:

<body onbeforeunload=
 "ajaxRequest('UnlockQuery.ashx?QueryID=<%= Session["QueryId"] %>&
 UserID=<%= Session["UserID"] %>')">

This is not working:

<body id="uxBodyTag" onbeforeunload=
 "ajaxRequest('UnlockQuery.ashx?QueryID=266&amp;UserID=11631');"> 

This is created using:

uxBodyTag.Attributes["onbeforeunload"] += 
 "ajaxRequest('UnlockQuery.ashx?QueryID=" + 
 queryId.ToString() + "&UserID=" + Session["UserID"].ToString() + "');";

The code being called is this:

function ajaxRequest(url)
{
    xmlhttp=null;
    if (window.XMLHttpRequest)
    {   // code for all new browsers
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {   // code for IE5 and IE6
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp!=null)
    {
        xmlhttp.onreadystatechange=null;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(null);
    }
}

EDIT:

It appears to only fail when subsequent calls are made to the same unlock. I think this may be an AJAX issue....

Was it helpful?

Solution

Adding

&date=DateTime.now.Ticks.ToString()

seems to have fixed it. I don't think IE7 likes it when the same AJAX call comes in and the previous hasn't been "resolved" (the page is disposed before the AJAX call returns).

Thanks to all that provided help.

OTHER TIPS

For the means of debugging, we tried:

alert(url);
xmlhttp.open("GET",url,true);

which gave the expected result of:

UnlockQuery.ashx?QueryID=319&UserID=11648

Now we can check what the server has to say through:

xmlhttp.onreadystatechange = function() { 
  if (this.readyState == 4) alert(this.status + ": " + this.StatusText); 
};

EDIT:

As it turns out, the browser cache was the reason for the unexpected results. I suggest to forbid caching the AJAX page through appropriate HTTP headers (Pragma, Cache-Control, Expires).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top