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.

Ibu
  • 42,752
  • 13
  • 76
  • 103
Vpp Man
  • 2,384
  • 8
  • 43
  • 74

5 Answers5

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>
Aaron J Spetner
  • 2,117
  • 1
  • 18
  • 30
14

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

<input type="submit" formaction=”differentThanNormalAction.php”>
Noumenon
  • 5,099
  • 4
  • 53
  • 73
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

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • This [article](https://mentaljetsam.wordpress.com/2008/06/02/using-javascript-to-post-data-between-pages/) goes one step further, and provides a fairly generic implementation. – jpaugh Oct 05 '16 at 19:00
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.

Jakub Arnold
  • 85,596
  • 89
  • 230
  • 327
0
<form onreturn="someJavascriptFunction()" action="" method="">

creating a js function able to open this preview page

Bernat
  • 1,537
  • 3
  • 18
  • 40