Thursday, March 12, 2009

Pop-up window upon submitting PHP Form

Context:
Suppose you have a form with 2 different buttons :
1) "Save Post" - on click, processes the data in the form, refreshes the current page (but displays an empty form).
2) "View All Posts" - on click, processes the data in the form, opens a pop-up window, gathers information based on the posted form data from the main window.Currently we are concerned with button (2).

PHP Code:
<form name="mainForm" action="" method="post">
<input name="email">
<input type="password" name="password">
<input name="mypost">
<input type="submit" name="button1" value="Save Post">
<button type="button" onClick="return viewTempAds()">View All</button>
</form>

Javascript Code:
function viewAllPosts() {
document.forms['mainForm'].action="viewAllPosts.php";
document.forms['mainForm'].target="popup";
document.forms['mainForm'].onSubmit="window.open('','popup','menubar=no,width=600')";
document.forms['mainForm'].submit();
}

Explanation:

Both buttons 1 and 2 require the form to carry out different actions after submitting. As such, we can dynamically change the value of the form action by using Javascript. We set the value of the action value to the desired page that we wish to display in the pop-up, and we set the form value of onSubmit to open a new window. We are also submitting the form remotely in the Javascript function.

No comments:

Post a Comment