Monday, May 3, 2010

Stopping a postback on client side with Ajax

Requirement was - on click of a button I wanted to get an alert and then based on logic i either wanted to do a postback or stop it.
Initial code
btn.onClientClick="return validate();"
Javascript code looked like this
function validate()
{
alert('some message');
if(some condition)
return true;
else
return false;
}
I had ajax post back on my button click which i wanted to stop when false is returned from validate function. But with above code it never posted back not even if the function returned true.
Ok! What went wrong
The code btn.OnClientClick = "return validate();" would get rendered as
input type="submit" onclick="return validate(); __doPostback(..)"
So what is happening is whether the javascript function returns true or false it doesnt matter, __doPostBack will never get called.
Lets now change it to make it work
btn.OnClientClick="if(!return validate()) return false;"
This renders
input type="submit" onclick=if(!validate()) return false; __doPostBack(..)"
So only when the validate() function returns false will it execute the first statement and will return from there else it will go to __doPostBack and cause a post back to happen.
Took me some time to figure this out and it just goes to prove that common sense is actually not so common ;-)

No comments: