views:

29

answers:

1

I have an ASP.NET application which uses XMLHTTPRequest to call a server side method when the user closes the browser(the requirement is I need to send a email when the user closes the browser). The code works perfectly when I have an Javascript alert. But it doesnt work when I remove the alert button. I read another article in StackOverflow here which has similar issues. Can someone tell me a work around for this which guarantees that my server side code is executed when the user closes the browser. Please find the code snippet below.

var ajaxRequest;

    window.onbeforeunload = function(e) {
        //function ConfirmClose(e) {

        var evtobj = window.event ? event : e;
        if (evtobj == e) {
            //firefox
            if (!evtobj.clientY) {
                AjaxRequest();
                //evtobj.returnValue = message;
            }
        }
        else {
            //IE
            if (evtobj.clientY < 0) {
                AjaxRequest();
            }
        }
    }

function AjaxRequest() {
        var url = "closing.aspx?function=EmailUnsubmittedApplication";
        if (window.XMLHttpRequest) {
            AJAX = new XMLHttpRequest();
        }
        else {
            AJAX = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (AJAX) {
            AJAX.open("POST", url, false);
            AJAX.send(null); 
            return AJAX.responseText;
        }
        else {
            return false; 
        } 
    } 
A: 

one thing you forget is to bind onreadystatechange with the xmlhttprequest object

AJAX.onreadystatechange = function() {
                if(AJAX.readyState == 4)
                {       
                        var response = AJAX.responseText;
                }
        }
Pranay Rana
How is doing something when the response gets back going to make sure the response gets back before the browser closes?
David Dorward
i think its valid that he foget to attache onready event handler
Pranay Rana
Hi David, Pranay - I'm closing the browser window using X and will the browser wait for onreadystatechange event to complete. David - Do you know how to handle the browser close until the server returns a response.
Kannabiran
i think you have to wait for unload event in javascrpt
Pranay Rana

related questions