Wednesday, March 28, 2012

Disable a button using AJAX

I saw this being discussed a couple of time but I wasn't able to figure out a solution. I got a webservice which is fired async by a button on my webform, now I need to disable the button to pretend ppl clicking multiple times on it. I tried it with that Javascript (added it to my .aspx in designer mode):

<scripttype="text/javascript">var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_initializeRequest(InitializeRequest);

prm.add_endRequest(EndRequest);

var postBackElement;

//fired when the update starts

function InitializeRequest(sender, args) {

postBackElement = args.get_postBackElement();

$get('<%= Button1.ClientID %>').enabled =false;

}

//fired when the update ends

function EndRequest(sender, args) {

$get('<%= Button1.ClientID %>').enabled =true;

}

</script>

However, my browser is throwing the error:

Error: prm has no properties
Source File:http://localhost:3889/solution/site.aspx
Line: 48

Anyone knows how to do it properly? Thanks a lot!

My guess is that your above code is firing too early and so when you call the getInstance() you're getting a null value. Try wrapping the var prm= and the prm.add_ calls inside function pageLoad() so that it fires after everything's been initialized.


The Page requestManager does not intercept the WebService Calls. Try Something like this.

For Example if have a button.

<input id="btnFire" type="button" value="ClickMe" onclick="FireWs" /
and JS:

function fireJs()
{

$get('btnFire').disabled = true:

//Now Call Your WS
WS.YourMethod(function()
{
//In the success handler enable your button
$get('btnFire').disabled = false:
}
);
}


To keep pages cleaner, I am also a fan of emitting JavaScript from the codebehind. Just add an attribute to a control like this:

dim controlUniqueID as string = ctype(me.findcontrol("myDisabledControl"), myDisabledControlType).uniqueID ' lets the JavaScript find any control on the page

submitButton.attribute.add("OnClick", "add a reference to a javascript function, or put inline code here.")

----

For more complex functions, I will register a javaScript function library and then reference methods in it.

cheers

No comments:

Post a Comment