PHP: How to change action of a form according to button pressed/clicked in php (opencart)?


I have a form with preview option before submitting the form. I am trying to change form action on click of preview button. Following is my code:

<form action="<?php echo $action; ?>" id="form" method="post" enctype="multipart/form-data" class="form-horizontal">
 <input type="text" name="to_name" value="<?php echo isset($_SESSION['to_name']) && !empty($_SESSION['to_name']) ? $_SESSION['to_name'] : $to_name; ?>" id="input-to-name" class="form-control" />
 <input type="submit" name="btn_preview" id="preview" class="btn btn-primary" value="Preview" />
 <input type="submit" name="btn_submit" value="Submit" class="btn btn-primary" />

<script type="text/javascript">
 $("#preview").click(function() {
  $("#form").attr("action", "<?php echo $action2; ?>");

public function index() {
 if(($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate() && isset($this->request->post['btn_preview']) && $this->request->post['btn_preview'] == 'Preview'){
  $data['action2']  = $this->url->link('account/voucher/preview', '', 'SSL');
  $data['action2']  = $this->url->link('account/voucher', '', 'SSL');

 $this->response->setOutput($this->load->view('default/template/account/voucher.tpl', $data));


In index() method variable action is defined but the problem is I have to click 2 times to get the preview button work, first time the $action2 have value of else condition which is $data['action2'] = $this->url->link('account/voucher', '', 'SSL'); . How can I fix this ?