How to handle form submission?

I’m new to wordpress and hence facing some issues.

The use case scenario is as follows:

  1. A user is displayed an application form to start a club in his school.
  2. The user fills the form and hits the ‘Submit’ button.
  3. The form needs to be validated.
  4. If the validation is successful, then data is stored in custom table club_details in db and the user is shown some message(eg: Thanks for submission. Your application is sent to the admin for approval.) else appropriate error messages are shown to the user.
  5. The admin goes to the WordPress admin panel to approve the pending requests for the club. (The data is fetched from db and shown to the admin).

I have done the following:

  • for 1) I have created a application form/page using the WordPress HTML editor.
  • for 3) I have a javascript file (validation.js) that has the validation code.
  • for 4) I have a php file (club-functions.php) that has a function storeInDB() to store the application details in custom table in db.
  • for 5) I have created my own plugin folder and added a php file (club.php) that displays the application details to the admin on the WordPress admin panel.

I’m stuck up at the following place: How to handle the form submission. Where should I place the code that calls the javascript’s validate function and later calls the storeInDB() function.

Please provide me some suggestions on how do I achieve this and is this approach good?
Thanks a lot in advance.

2

You should use the wp_ajax or the wp_ajax_nopriv function.

First of all you should put the the admin ajax url as the action attribute value in the submission form.

<form id="" action="<?php echo admin_url('admin-ajax.php'); ?>" method="post" class="form" >

That way the the form will be submitted to the admin-ajax.php by default (without JavaScript). You can use JavaScript to make it work using AJAX.

Next is the function that will use the submitted data. Inside the form, put a wp_nonce_field and a hidden input with the name action. My action value is add_transfer.

<?php wp_nonce_field('add_transfer','security-code-here'); ?>
<input name="action" value="add_transfer" type="hidden">

You can put the function that will handle this form in the functions.php or in your plugin file. You can use wp_ajax_ + the action name if this is a form only for logged in users. For non logged in users, use wp_ajax_nopriv + the action name instead.

add_action('wp_ajax_add_transfer', 'process_add_transfer');

function process_add_transfer() {
    if ( empty($_POST) || !wp_verify_nonce($_POST['security-code-here'],'add_transfer') ) {
        echo 'You targeted the right function, but sorry, your nonce did not verify.';
        die();
    } else {
        // do your function here 
        wp_redirect($redirect_url_for_non_ajax_request);
    }
}

Leave a Comment