Submit form to another page (which is different from the page used in ACTION)
Asked Answered
E

5

28

I have a form like this:

index.php

<form method="post" action="send.php">
  <textarea name="msg" id="msg"></textarea>
  <input type="submit" value="Send" />
</form>

So, if I enter something in textarea and clicked on "Send", it is submitted to "send.php" page. But I want to include another button for previewing it. That is, when this button is clicked, the above form is submitted to "preview.php" which will be opened in a new blank window/tab (original page ie. index.php will be there intact). This is to display a preview of the message, that the user is going to send.

I do not know how to do this.

Echoechoic answered 4/1, 2012 at 18:3 Comment(0)
E
34

Use Javascript to temporarily change the action and target:

<form method="post" action="send.php" id="idOfForm">
  <textarea name="msg" id="msg"></textarea>
  <input type="submit" value="Send" />
</form>
<button onclick="doPreview();">Preview</button>
<script type="text/javascript">
    function doPreview()
    {
        form=document.getElementById('idOfForm');
        form.target='_blank';
        form.action='preview.php';
        form.submit();
        form.action='send.php';
        form.target='';
    }
</script>
Enenstein answered 4/1, 2012 at 18:14 Comment(2)
I didn't know you can have target blank for form! It's awesome!Selassie
@VppMan It would be nice to see, how did you mix it.Joachima
F
14

There is now an attribute for the submit input that handles this:

<input type="submit" formaction=”differentThanNormalAction.php”>
Frieda answered 19/2, 2017 at 15:52 Comment(0)
O
6

Give your form an ID (form1). The action of the current form can be controlled like this:

function setPreview() {
    $('#form1').attr('target','_blank')
    $('#form1').attr('action','http://yourpreviewurl.php')
    $('#form1').submit()
}

function setSubmit() {
    $('#form1').attr('target','')
    $('#form1').attr('action','http://yourposturl.php')
    $('#form1').submit()
}

Have two buttons, both type="button", one to call setPreview and another to call setSubmit

Orientate answered 4/1, 2012 at 18:10 Comment(1)
This article goes one step further, and provides a fairly generic implementation.Cystocarp
G
1

You can use JavaScript to change the action of the form when the button is clicked and then submit it.

Or simply submit the form via AJAX and then redirect after you get a response.

Glut answered 4/1, 2012 at 18:9 Comment(0)
P
0
<form onreturn="someJavascriptFunction()" action="" method="">

creating a js function able to open this preview page

Prefigure answered 4/1, 2012 at 18:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.