WordPress form handling with admin-ajax
-
There is the official documentation of the form handling with
admin_post_{$action}
https://developer.www.ads-software.com/reference/hooks/admin_post_action/
But I don’t know why there is none about
admin_ajax_{$action}
which I also couldn’t find a really relevant and detailed explanation when I google.Assume I have the below minimal example code:
<form action="<?php echo admin_url( 'admin-ajax.php' ) ?> " method="post"> <input type="hidden" name="action" value="capture_form"> <input id="fname" placeholder="First Name" type="text" name="fname"> <input id="lname" placeholder="Last Name" type="text" name="lname"> <input type="submit" value="Submit"> </form>
With this in the
functions.php
:add_action( 'admin_ajax_capture_form', 'capture_form' ); function capture_form() { // Do something } wp_enqueue_script( 'example', 'https://www.example.com/script.js', array(), null, true );
And JavaScript that uses
fetch()
:const firstName = document.getElementById('fname').value, lastName = document.getElementById('lname').value, data = { firstName: firstName, lastName: lastName }; fetch('https://www.example.com/form-handling.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), });
My question now is:
1) How do I send thedata
to the PHP file (https://www.example.com/form-handling.php
) that would be used to handle the data? For the old school method, I think it should be something like the below but I don’t know how to send it withfetch()
:const request = new XMLHttpRequest(); request.send(data);
2) How do I get the data that is sent by
fetch()
and store it in the variables in the PHP file(
https://www.example.com/form-handling.php
) ?$first_name = // How to get the <code>const firstName</code> from the JavaScript? $last_name = // How to get the <code>const lastName</code> from the JavaScript?
- The topic ‘WordPress form handling with admin-ajax’ is closed to new replies.