Executing a event or function on each postback





2.00/5 (1 vote)
Executing a event or function on each postback
Introduction
Executing a event or function on each postback
Background
Problem: Suppose we want to call an javascript function or an event on each postback eg. show a loading image on each every postback. Using jQuery we can bind a function on form submit. However, it will only work with buttons and input type submit. This will fail when an auto postback occurs or postback occurs through some linkbutton.
Asp.net performs each postback using a javascript function which it inserts in its one and only one form tag. So we will be tweaking this function for our own purpose
Using the Code
<script type="<a class="attribute-value">text/javascript">
<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
]]>
</script>
Above code is what inserted by ASP.net engine.
function doSomething() {----};
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
doSomething();
theForm.submit();
}
}
We will insert our own __doPostBack function at end of form tag so that javascript engine overrides the previous one.
<form > --code by ASP.net --- page content--- --- modified script--- </form>