I’m new to wordpress and hence facing some issues.
The use case scenario is as follows:
- A user is displayed an application form to start a club in his school.
- The user fills the form and hits the ‘Submit’ button.
- The form needs to be validated.
- 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. - 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 functionstoreInDB()
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.
You should use the
wp_ajax
or thewp_ajax_nopriv
function.First of all you should put the the admin ajax url as the action attribute value in the submission 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 isadd_transfer
.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, usewp_ajax_nopriv
+ the action name instead.first, let me tell you that javascript validation works on client side. so if the user, disables js, you’re going to have problems.
so, you should also validate the input values, server-side.
with that in mind:
The js code can be called directly from the page where the form is. onsubmit attribute is the usual way to call it.
example
page.php
This can be also your custom template page or single.php. in this case, 99 is the ID of the specific page you want to indicate to the user if it was approved or had an error.