Aborting AJAX Requests

The ASP.NET AJAX script library provides a simple way to abort asynchronous postback requests in cases where users decide they don't need data they originally requested.  This can be done without tying into different PageRequestManager events.  Instead, the abortPostBack() method can be called as shown in the code that follows.  For more information on aborting AJAX requests you can read my latest .NET Insight article here.

function btnAbort_Click()
{
    
var prm Sys.WebForms.PageRequestManager.getInstance();
    if 
(prm.get_isInAsyncPostBack())
    {
        prm.abortPostBack()
;
        alert
("Postback aborted!");
    
}
    
else
    
{
        
alert("No postback operation is in progress.");
    
}
}

comments powered by Disqus

4 Comments

  • Not really a cancel as much as a don't show me what you did button - looks like the original request would still be processed. Wonder if in your Server Code you could pick up the Response.IsClientConnected property and roll back any changes to the DB it might have made.

  • That's correct.  This simply aborts things on the client-side since the initial message has already been sent to the server and would of course be processed.  I haven't tried checking the IsClientConnected property to "truly" abort things on the server-side.  Something to look into though.
    Operations like inserts and updates would typically occur more quickly and the user likely wouldn't have time to abort  anything (unless there's a lot of pre-processing going on for business rules or something).  However, if they're trying to grab a report that takes a while to generate then the abort would come into play more often I think.

  • If a client wants to delete 2 records by pressing Delete button, then they click btnAbort when 1 record has been deleted. Should we put a roll back action for a abort button or not ?

  • Good question! In that case I'd actually consider letting them know what changes were made. Keep in mind that "abort" as mentioned here is simply a client-side abort. The server-side process is still running so more than likely both records would be deleted. But, handling that situation is something that should definitely be taken into consideration. Whether or not you let them know what actually happened would be up to your app requirements and rules.

    One final note, I don't know that I'd give the ability to abort a delete operation unless it was an extremely time consuming type of activity. I normally use abort more in situations where a long-running report generation process is going, a remote service is called to get data, etc. But, each situation is different of course.

Comments have been disabled for this content.