Javascript – Check what control initiated AJAX Request

ajaxasp.netjavascriptjquerypagerequestmanager

asp.net 2.0 / jQuery / AJAX

<script type="text/javascript">
//updated to show proper method signature

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(hideMessage);

function hideMessage(sender, args)
{
    var ctl = args.get_postBackElement();
    //check if ctl is the disired control
    //hide user notification message
}
</script>

i have several controls on the page that might initiate the AJAX request, but i only want my js to fire when i click one particular button. how do i check what control initiated the request so i can fire JS accordingly.

EDIT: I worked around it, but I'd still like to know if I can do it this way.

Clarification: I can't call the JS from onclick event, because the page is inside of the UpdatePanel, and i only want the JS to execute when AJAX Request ends and it was triggered by one particular button on the page. On server side, i set the myLabel.Text to some text, and then js checks if the $(myLabel.CliendID)'s innerHTML is not blank and fires the js. checking the innerHTML is my work-around since i can't figure out how to check the "sender" of AJAX Request. Hope this makes more sense now.

edit2: I've read some documentation, and turns out you CAN check the "sender" control.

Thank you.

Best Solution

This is what I am doing in my code to identify what control has initialized the request. All javascript code.

function pageLoad() {
    if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
        Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(initializeRequest);
    }
}
function endRequestHandler(sender, args) {
    if (sender._postBackSettings.sourceElement.id == '<%= gvResults.ClientID %>')        {
        //do something because of this...
    }
}
function initializeRequest(sender, args) {
    if (CheckForSessionTimeout()) {
        args.set_cancel(true);
    }
    else {
        if (sender._postBackSettings.sourceElement.id == '<%= gvResults.ClientID %>') {
             //do something because of this
        }
    }
}

EDIT
Here is the method of checking for timeout on the client side.

var sessionTimeoutDateTime = new Date();
    var sessionTimeoutInterval = <%= this.SesstionTimeoutMinutes %>;

    function CheckForSessionTimeout() {
        var currentDateTime = new Date()
        var iMiliSeconds = (currentDateTime - sessionTimeoutDateTime);
        if (iMiliSeconds >= sessionTimeoutInterval) {
            ShowSessionTimeout();
            return true;
        }
        return false;
    }