3

In this scenario only the Javascript function works. But I want to run JavaScript function(onclick event) and form action (my PHP backend) at the same time, how to do that?

<tr id="tr4" class="table-danger">
  <td>Geethan</td>
  <td>
    <form action='include/action.php?user_id=3' method='post'>
      <input id="tr4_btn" class="btn btn-warning" type="button" value="Take action" onclick="takeaction(this.id,'tr4','tr4_i')" />
      <i id="tr4_i" class="fa " style="color:green;"></i>
    </form>
  </td>
</tr>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
kasunk
  • 37
  • 4
  • add type="submut" try? – Антон Прохоров Nov 23 '20 at 07:13
  • [This post](https://stackoverflow.com/questions/6799533/how-to-submit-a-form-with-javascript-by-clicking-a-link) may help, you just need to make the input `type='submit' value='submit'` – Ricardo Sanchez Nov 23 '20 at 07:19
  • What do you mean with "at the same time"? You want to tell the server via [JavaScript to execute a PHP script](https://stackoverflow.com/questions/958040/what-is-ajax-really/958057) while the page **doesn't reload or link to another page**? Or you want to execute the JavaScript first and after its finished make the request so PHP processes it while it loads another page? – Definitely not Rafal Nov 23 '20 at 07:20
  • At the same time makes no sense. I'm guessing you either want to run js first and the submission after it's done (that approach is explained in Bai's answer) or you need AJAX as !Rafal mentions. Either way, I'd suggest editing the question to reflect your actual needs (for any future readers searching for a solution to the same problem). – El_Vanja Nov 23 '20 at 08:04

1 Answers1

2

Because when you submit the form, the website will be redirect to form action, so your action if not completed, it will be cancelled. You can try this way (jQuery).

function takeaction(id,$val1,$val2){
     var $this = jQuery('#'+id);
     var $form = $this.parents('form');
     //...your javascript code at here
     // after run your code
    $form.submit();// to submit form
}
Bai Nguyen
  • 814
  • 7
  • 16