In the last article I talked about Detecting Popup Blockers using JavaScript. In this article we will see that how we can make a post back from the child window to the parent window using simple JavaScript. Consider a situation that you make a small popup window and fill out a small form and when you press the submit button you want to see the changes reflected on the parent page which made that popup. One way is to refresh the parent page and the new information will be loaded but smarter way is to make use of the post back.
In the last article I talked about Detecting Popup Blockers using JavaScript. In this article we will see that how we can make a post back from the child window to the parent window using simple JavaScript. Consider a situation that you make a small popup window and fill out a small form and when you press the submit button you want to see the changes reflected on the parent page which made that popup. One way is to refresh the parent page and the new information will be loaded but smarter way is to make use of the post back.
The Parent Window:
The parent window only contains a hyperlink which is when clicked opens the child window. Let's take at the code below:
<form id="Form1" method="post" runat="server"> <P>This is Parent Window</P> <a href="#" onclick="OpenWindow();">Open Child Window</a> </form> <script language="javascript"> function OpenWindow() { window.open('ChildWindow.aspx','MyChild','width=300,height=200'); } </script> |
As you can see that the parent window code is pretty straight forward. All it does is opens a new window.
The Child Window:
The Child window will contain a simple link which is when clicked does the post back on the parent page. In the code below we have defined a function named DoPostBack(); which simply submits the parent form. Window.Opener will return you a reference to the parent window and if there is no parent window than it will return null. Self.Close() simply closes the child window.
<form id="Form1" method="post" runat="server"> <P>This is my Child Window </P> <a href="#" onclick="DoPostBack();"> Do a Postback </a> </form> </body> </HTML> <script language="javascript"> function DoPostBack() { window.opener.document.forms(0).submit(); self.close(); } |
You can also easily check that if the post back occurred or not by using these lines in the parent page.
private void Page_Load(object sender, System.EventArgs e) { if(Page.IsPostBack == true) { Response.Write("PostBack from Client"); // When the link from the child window is clicked this line is executed } } |
I hope you liked the article, happy coding!