0

I have created a HTML form inside a PHP file in Wordpress similar as below:

<form>
  <input id="currentProjectId" type="hidden" />
  <input id="expertiseCheck" class="custom-control-input" type="checkbox"/>
  <label class="custom-control-label" for="expertiseCheck">Contribute with expertise</label>
  <button class="btn btn-primary">Submit</button>
</form>

Now, I want to execute a PHP function when the form is submitted that is able to access the values inserted in the form (such as in the input expertiseCheck or currentProjectId) and do some action after the form has been submitted (belonging to other plugins).

I have tested how to call a function from functions.php using wp-admin or wp-ajax actions. However, I would like to know a method that does not redirect to wp-admin.php or other pages but that instead processes the submission in the background and stays on the same page, as a javascript function would do (but I can not use one because I need to call PHP functions)

Thank you in advance!

  • 1
    "as a javascript function would do (but I can not use one because I need to call PHP functions)" - That's quite literally what AJAX (and wp_ajax) functions are for. Set up a javascript `onsubmit` function to handle to form's submission, and make an AJAX request which can run any PHP functions you want. There are tons of tutorials on [Submit a WordPress form with AJAX](https://www.smashingmagazine.com/2018/02/submitting-forms-without-reloading-ajax-implementation-wordpress/) that will 100% do what you're asking for. – Xhynk Mar 09 '21 at 21:09
  • I have not been able to use wp_ajax because it redirects me to admin/wp_ajax.php when I submit the form. I just need to call a function (even if it is on the same PHP file instead of in functions.php) when the form is submitted. – Angel Luis Mar 10 '21 at 15:52
  • You need to prevent the default submit action with `preventDefault();` in your JavaScript: https://stackoverflow.com/questions/25983603/how-to-submit-an-html-form-without-redirection – Xhynk Mar 10 '21 at 18:24

0 Answers0